| 1 | """Host-fetched X envelope (``--x-posts``): the U5 contract. |
| 2 | |
| 3 | The envelope is a file of flat post rows the hosting model fetched through its |
| 4 | X connector. It is validated strictly at the top level (fail closed, exit 2) |
| 5 | and leniently per row (drop and count), every citation is rebuilt from a |
| 6 | numeric id and a grammar-valid handle, and the envelope replaces the engine's |
| 7 | X fetch for exactly one serve. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import contextlib |
| 13 | import hashlib |
| 14 | import io |
| 15 | import json |
| 16 | import os |
| 17 | import re |
| 18 | import stat |
| 19 | import sys |
| 20 | from contextlib import redirect_stderr, redirect_stdout |
| 21 | from datetime import date, datetime, timedelta, timezone |
| 22 | from pathlib import Path |
| 23 | from unittest import mock |
| 24 | |
| 25 | import pytest |
| 26 | |
| 27 | import last30days as cli |
| 28 | from lib import dates, env, health, html_render, pipeline, render, schema, x_api, x_envelope |
| 29 | |
| 30 | TOPIC = "ai agents" |
| 31 | FROM, TO = dates.get_date_range(30) |
| 32 | SUBJECT = "steipete" |
| 33 | RELATED = "peer1" |
| 34 | ACCOUNT_ID = "acct-987654321-SECRET" |
| 35 | |
| 36 | |
| 37 | # --------------------------------------------------------------------------- |
| 38 | # Fixture builders |
| 39 | # --------------------------------------------------------------------------- |
| 40 | |
| 41 | |
| 42 | def _day(offset: int) -> str: |
| 43 | return (date.fromisoformat(TO) - timedelta(days=offset)).isoformat() |
| 44 | |
| 45 | |
| 46 | def _snowflake(day: str, *, hour: int = 12, minute: int = 0, low: int = 0) -> str: |
| 47 | when = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc) |
| 48 | when += timedelta(hours=hour, minutes=minute) |
| 49 | ms = int(when.timestamp() * 1000) |
| 50 | return str(((ms - x_api._SNOWFLAKE_EPOCH_MS) << 22) | (low & ((1 << 22) - 1))) |
| 51 | |
| 52 | |
| 53 | # Day offsets with irregular gaps so a normal fixture never reads as generated. |
| 54 | _OFFSETS = (1, 2, 4, 9, 11, 18) |
| 55 | |
| 56 | |
| 57 | def _row( |
| 58 | n: int, |
| 59 | handle: str = SUBJECT, |
| 60 | text: str = "ai agents are shipping fast", |
| 61 | *, |
| 62 | created_at: str | None | object = "auto", |
| 63 | likes: int = 10, |
| 64 | **extra, |
| 65 | ) -> dict: |
| 66 | day = _day(_OFFSETS[n % len(_OFFSETS)]) |
| 67 | pid = _snowflake(day, hour=8 + n, minute=(n * 17) % 60, low=(n + 1) * 104729) |
| 68 | row = { |
| 69 | "id": pid, |
| 70 | "author_handle": handle, |
| 71 | "created_at": f"{day}T{8 + n:02d}:{(n * 17) % 60:02d}:00Z" if created_at == "auto" else created_at, |
| 72 | "text": text, |
| 73 | "likes": likes, |
| 74 | "reposts": 1, |
| 75 | "replies": 0, |
| 76 | "quotes": 0, |
| 77 | } |
| 78 | if created_at is None: |
| 79 | row.pop("created_at") |
| 80 | row.update(extra) |
| 81 | return row |
| 82 | |
| 83 | |
| 84 | def _call(lane: str = "topic", handles=(), posts=()) -> dict: |
| 85 | return {"lane": lane, "handles": list(handles), "posts": list(posts)} |
| 86 | |
| 87 | |
| 88 | def _envelope(calls, **over) -> dict: |
| 89 | payload = { |
| 90 | "schema": x_envelope.SCHEMA, |
| 91 | "generated_at": datetime.now(timezone.utc).isoformat(), |
| 92 | "topic": TOPIC, |
| 93 | "window": {"from": FROM, "to": TO}, |
| 94 | "provider": "x-connector", |
| 95 | "status": "ok", |
| 96 | "calls": list(calls), |
| 97 | } |
| 98 | payload.update(over) |
| 99 | return payload |
| 100 | |
| 101 | |
| 102 | def _write(tmp_path: Path, payload, name: str = "posts.json") -> str: |
| 103 | path = tmp_path / name |
| 104 | text = payload if isinstance(payload, str) else json.dumps(payload) |
| 105 | path.write_text(text, encoding="utf-8") |
| 106 | return str(path) |
| 107 | |
| 108 | |
| 109 | def _read(path: str, *, topic: str = TOPIC, handles=(SUBJECT,), related=(), window=(FROM, TO)): |
| 110 | return x_envelope.read(path, window, topic, handles=list(handles), related=list(related)) |
| 111 | |
| 112 | |
| 113 | def _basic(tmp_path: Path, **over) -> str: |
| 114 | """Topic call with two rows plus a from call with one subject row.""" |
| 115 | return _write(tmp_path, _envelope([ |
| 116 | _call("topic", posts=[_row(0, "alice", "ai agents review"), _row(1, "bob", "agents everywhere")]), |
| 117 | _call("from", handles=[SUBJECT], posts=[_row(2, SUBJECT, "shipping my agent today")]), |
| 118 | ], **over)) |
| 119 | |
| 120 | |
| 121 | def _plan(sources=("x",)) -> dict: |
| 122 | return { |
| 123 | "intent": "general", |
| 124 | "freshness_mode": "balanced_recent", |
| 125 | "cluster_mode": "story", |
| 126 | "subqueries": [{ |
| 127 | "label": "primary", |
| 128 | "search_query": TOPIC, |
| 129 | "ranking_query": f"What are people saying about {TOPIC}?", |
| 130 | "sources": list(sources), |
| 131 | }], |
| 132 | "source_weights": {s: 1.0 for s in sources}, |
| 133 | } |
| 134 | |
| 135 | |
| 136 | def _two_x_plan() -> dict: |
| 137 | plan = _plan() |
| 138 | plan["subqueries"].append({ |
| 139 | "label": "angle", |
| 140 | "search_query": "agent frameworks", |
| 141 | "ranking_query": "Which agent frameworks are people using?", |
| 142 | "sources": ["x"], |
| 143 | }) |
| 144 | return plan |
| 145 | |
| 146 | |
| 147 | @contextlib.contextmanager |
| 148 | def _no_backend(): |
| 149 | with mock.patch("lib.env.x_backend_chain", return_value=[]), \ |
| 150 | mock.patch( |
| 151 | "lib.pipeline._fetch_x_backend", |
| 152 | side_effect=AssertionError("no X backend may be called on an envelope run"), |
| 153 | ) as fetch: |
| 154 | yield fetch |
| 155 | |
| 156 | |
| 157 | def _run(envelope, *, config=None, x_handle=None, x_related=None, depth="default", |
| 158 | plan=None, requested=("x",), topic=TOPIC, **kwargs): |
| 159 | with _no_backend(): |
| 160 | return pipeline.run( |
| 161 | topic=topic, config=dict(config or {}), depth=depth, |
| 162 | requested_sources=list(requested) if requested is not None else None, |
| 163 | mock=False, x_handle=x_handle, x_related=x_related, |
| 164 | external_plan=plan or _plan(), x_posts=envelope, |
| 165 | web_backend="none", save_dir="", **kwargs, |
| 166 | ) |
| 167 | |
| 168 | |
| 169 | def _capture(fn): |
| 170 | err = io.StringIO() |
| 171 | with redirect_stderr(err): |
| 172 | result = fn() |
| 173 | return result, err.getvalue() |
| 174 | |
| 175 | |
| 176 | # --------------------------------------------------------------------------- |
| 177 | # Ingestion: happy path and row trust (R9, R10, AE5, AE6, AE6a) |
| 178 | # --------------------------------------------------------------------------- |
| 179 | |
| 180 | |
| 181 | class TestIngestion: |
| 182 | def test_valid_envelope_serves_topic_and_from_lanes_without_a_backend(self, tmp_path): |
| 183 | envelope, stderr = _capture(lambda: _read(_basic(tmp_path))) |
| 184 | assert envelope.accepted == 3 and envelope.total == 3 |
| 185 | assert envelope.status == "ok" |
| 186 | assert [c.lane for c in envelope.lane_calls] == ["from"] |
| 187 | assert len(envelope.topic_items) == 2 |
| 188 | assert "host-fetched X: accepted 3 of 3" in stderr |
| 189 | assert "lanes: topic 2, from 1, mention 0, related 0" in stderr |
| 190 | |
| 191 | with _no_backend() as fetch: |
| 192 | report = pipeline.run( |
| 193 | topic=TOPIC, config={}, depth="default", requested_sources=["x"], |
| 194 | mock=False, x_handle=SUBJECT, external_plan=_plan(), x_posts=envelope, |
| 195 | web_backend="none", save_dir="", |
| 196 | ) |
| 197 | fetch.assert_not_called() |
| 198 | urls = {item.url for item in report.items_by_source["x"]} |
| 199 | assert len(urls) == 3 |
| 200 | assert all(u.startswith("https://x.com/") for u in urls) |
| 201 | by_author = {item.author: item for item in report.items_by_source["x"]} |
| 202 | assert SUBJECT in by_author, "from-lane row must land under x" |
| 203 | assert report.source_status["x"].state == health.OK |
| 204 | assert "x" not in report.errors_by_source |
| 205 | |
| 206 | def test_lane_calls_are_served_on_quick_runs(self, tmp_path): |
| 207 | """The host already paid for the lanes: --quick must not drop them.""" |
| 208 | envelope = _read(_basic(tmp_path)) |
| 209 | report = _run(envelope, x_handle=SUBJECT, depth="quick") |
| 210 | by_author = {item.author: item for item in report.items_by_source["x"]} |
| 211 | assert SUBJECT in by_author, "from-lane row must land under x on a quick run" |
| 212 | assert len(report.items_by_source["x"]) == 3 |
| 213 | |
| 214 | def test_mention_lane_rows_reach_the_report(self, tmp_path): |
| 215 | envelope = _read(_write(tmp_path, _envelope([ |
| 216 | _call("topic", posts=[_row(0, "alice", "ai agents review")]), |
| 217 | # On-topic enough to clear the relevance floor: the report's X view is |
| 218 | # finalized after that floor, so an off-topic mention row would be pruned. |
| 219 | _call("mention", handles=[SUBJECT], posts=[_row(4, "fan", f"@{SUBJECT} love the ai agents work")]), |
| 220 | ]))) |
| 221 | assert envelope.lane_counts["mention"] == 1 |
| 222 | report = _run(envelope, x_handle=SUBJECT) |
| 223 | by_author = {item.author: item for item in report.items_by_source["x"]} |
| 224 | assert "fan" in by_author, "mention-lane row must land under x" |
| 225 | assert len(report.items_by_source["x"]) == 2 |
| 226 | |
| 227 | def test_from_row_gets_first_party_handling(self, tmp_path): |
| 228 | # A subject post that never repeats the topic must survive the |
| 229 | # relevance floor: that is what first-party handling means. |
| 230 | path = _write(tmp_path, _envelope([ |
| 231 | _call("topic", posts=[_row(0, "alice", "ai agents review")]), |
| 232 | _call("from", handles=[SUBJECT], posts=[_row(2, SUBJECT, "lunch was great")]), |
| 233 | ])) |
| 234 | envelope = _read(path) |
| 235 | report = _run(envelope, x_handle=SUBJECT) |
| 236 | authors = {item.author for item in report.items_by_source["x"]} |
| 237 | assert SUBJECT in authors |
| 238 | |
| 239 | def test_created_at_disagreeing_with_snowflake_is_date_mismatch(self, tmp_path): |
| 240 | # created_at inside the window; the snowflake decodes two months earlier. |
| 241 | early = (date.fromisoformat(FROM) - timedelta(days=60)).isoformat() |
| 242 | forged = _row(0, "alice") |
| 243 | forged["id"] = _snowflake(early, low=99) |
| 244 | path = _write(tmp_path, _envelope([_call("topic", posts=[forged, _row(1, "bob")])])) |
| 245 | envelope = _read(path) |
| 246 | assert envelope.counters["date-mismatch"] == 1 |
| 247 | assert envelope.accepted == 1 |
| 248 | |
| 249 | def test_off_domain_url_is_ignored_and_citation_rebuilt(self, tmp_path): |
| 250 | row = _row(0, "alice", url="https://evil.example/alice/status/1") |
| 251 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 252 | assert envelope.accepted == 1 |
| 253 | item = envelope.topic_items[0] |
| 254 | assert item["url"] == f"https://x.com/i/status/{row['id']}" |
| 255 | assert "evil.example" not in json.dumps(envelope.topic_items) |
| 256 | |
| 257 | def test_spoofed_subject_handle_with_off_domain_url_is_not_attributed(self, tmp_path): |
| 258 | """AE6a: the row is kept, its citation is rebuilt from the id, the |
| 259 | subject attribution is dropped, and handle-mismatch is counted.""" |
| 260 | row = _row(0, SUBJECT, "totally the subject", url="https://evil.example/x") |
| 261 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])])), handles=[SUBJECT]) |
| 262 | assert envelope.counters["handle-mismatch"] == 1 |
| 263 | item = envelope.topic_items[0] |
| 264 | assert item["author_handle"] == "" |
| 265 | assert item["url"] == f"https://x.com/i/status/{row['id']}" |
| 266 | |
| 267 | def test_url_handle_or_id_disagreement_is_handle_mismatch(self, tmp_path): |
| 268 | row = _row(0, SUBJECT) |
| 269 | row["url"] = f"https://x.com/someoneelse/status/{row['id']}" |
| 270 | other = _row(1, "bob") |
| 271 | other["url"] = "https://x.com/bob/status/1234567890" |
| 272 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row, other])]))) |
| 273 | assert envelope.counters["handle-mismatch"] == 2 |
| 274 | assert all(item["author_handle"] == "" for item in envelope.topic_items) |
| 275 | |
| 276 | def test_future_snowflake_is_dropped(self, tmp_path): |
| 277 | future = (date.today() + timedelta(days=40)).isoformat() |
| 278 | row = _row(0, "alice", created_at=None) |
| 279 | row["id"] = _snowflake(future) |
| 280 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row, _row(1, "bob")])]))) |
| 281 | assert envelope.accepted == 1 |
| 282 | assert envelope.counters["out-of-window"] == 1 |
| 283 | |
| 284 | def test_uniform_id_sequence_rejects_the_whole_envelope(self, tmp_path): |
| 285 | base = int(_snowflake(_day(10))) |
| 286 | step = 1 << 30 |
| 287 | rows = [] |
| 288 | for i in range(5): |
| 289 | row = _row(i, "alice", f"post {i}", created_at=None) |
| 290 | row["id"] = str(base + i * step) |
| 291 | rows.append(row) |
| 292 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=rows)]))) |
| 293 | assert envelope.status == "error" |
| 294 | assert envelope.accepted == 0 and envelope.topic_items == [] |
| 295 | report = _run(envelope) |
| 296 | assert report.source_status["x"].state == health.ERROR |
| 297 | assert "generated" in (report.source_status["x"].detail or "") |
| 298 | |
| 299 | def test_duplicate_ids_across_calls_first_occurrence_wins(self, tmp_path): |
| 300 | first = _row(0, "alice", "first copy") |
| 301 | second = dict(first, text="second copy", author_handle="bob") |
| 302 | envelope = _read(_write(tmp_path, _envelope([ |
| 303 | _call("topic", posts=[first]), |
| 304 | _call("topic", posts=[second]), |
| 305 | ]))) |
| 306 | assert envelope.counters["duplicate"] == 1 |
| 307 | assert envelope.accepted == 1 |
| 308 | assert envelope.topic_items[0]["text"] == "first copy" |
| 309 | |
| 310 | def test_missing_created_at_derives_date_from_snowflake(self, tmp_path): |
| 311 | row = _row(0, "alice", created_at=None) |
| 312 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 313 | assert envelope.accepted == 1 |
| 314 | assert envelope.topic_items[0]["date"] == _day(_OFFSETS[0]) |
| 315 | |
| 316 | def test_unparseable_created_at_is_ignored(self, tmp_path): |
| 317 | row = _row(0, "alice", created_at="yesterday-ish") |
| 318 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 319 | assert envelope.accepted == 1 |
| 320 | assert envelope.topic_items[0]["date"] == _day(_OFFSETS[0]) |
| 321 | |
| 322 | def test_row_outside_engine_window_is_dropped(self, tmp_path): |
| 323 | old = (date.fromisoformat(FROM) - timedelta(days=5)).isoformat() |
| 324 | row = _row(0, "alice", created_at=f"{old}T10:00:00Z") |
| 325 | row["id"] = _snowflake(old, hour=10) |
| 326 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 327 | assert envelope.accepted == 0 |
| 328 | assert envelope.counters["out-of-window"] == 1 |
| 329 | |
| 330 | def test_missing_id_or_text_is_dropped(self, tmp_path): |
| 331 | no_id = _row(0, "alice") |
| 332 | no_id.pop("id") |
| 333 | no_text = _row(1, "bob", text=" ") |
| 334 | non_numeric = _row(2, "carol") |
| 335 | non_numeric["id"] = "abc123" |
| 336 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[no_id, no_text, non_numeric])]))) |
| 337 | assert envelope.accepted == 0 |
| 338 | assert envelope.counters["missing-id-text"] == 3 |
| 339 | |
| 340 | def test_missing_username_keeps_row_with_i_status_url(self, tmp_path): |
| 341 | row = _row(0, "") |
| 342 | placeholder = _row(1, "unknown") |
| 343 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row, placeholder])]))) |
| 344 | assert envelope.accepted == 2 |
| 345 | assert envelope.counters["uncitable"] == 2 |
| 346 | urls = {item["url"] for item in envelope.topic_items} |
| 347 | assert urls == { |
| 348 | f"https://x.com/i/status/{row['id']}", |
| 349 | f"https://x.com/i/status/{placeholder['id']}", |
| 350 | } |
| 351 | |
| 352 | def test_handle_with_embedded_newline_is_rejected(self, tmp_path): |
| 353 | row = _row(0, "stei\npete") |
| 354 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 355 | assert envelope.topic_items[0]["author_handle"] == "" |
| 356 | assert envelope.counters["uncitable"] == 1 |
| 357 | |
| 358 | def test_control_characters_are_stripped_but_newlines_in_text_survive(self, tmp_path): |
| 359 | row = _row(0, "alice", text="line one\x07\x1b[31m\nline two ") |
| 360 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 361 | assert envelope.topic_items[0]["text"] == "line one[31m\nline two" |
| 362 | |
| 363 | def test_markdown_link_tail_and_comment_opener_are_defanged(self, tmp_path): |
| 364 | row = _row(0, "alice", text="read [this](https://evil.example) <!-- hidden --> ok") |
| 365 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 366 | text = envelope.topic_items[0]["text"] |
| 367 | assert "](" not in text and "<!--" not in text |
| 368 | assert "evil.example" in text, "the characters stay visible as evidence" |
| 369 | |
| 370 | def test_text_over_cap_is_truncated_and_counted(self, tmp_path): |
| 371 | row = _row(0, "alice", text="x" * (x_envelope.MAX_TEXT_CHARS + 50)) |
| 372 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 373 | assert envelope.counters["truncated"] == 1 |
| 374 | assert len(envelope.topic_items[0]["text"]) == x_envelope.MAX_TEXT_CHARS |
| 375 | |
| 376 | def test_extra_keys_are_ignored_and_counted_once(self, tmp_path): |
| 377 | row = _row(0, "alice", public_metrics={"like_count": 5}, entities={}, edit_history_tweet_ids=["1"]) |
| 378 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 379 | assert envelope.accepted == 1 |
| 380 | assert envelope.counters["extra-fields"] == 1 |
| 381 | item = envelope.topic_items[0] |
| 382 | assert item["engagement"]["likes"] == 10 |
| 383 | assert "public_metrics" not in item |
| 384 | |
| 385 | def test_rows_normalize_through_the_x_item_shape(self, tmp_path): |
| 386 | row = _row(0, "alice", "@bob @carol thoughts on ai agents?", likes=7) |
| 387 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 388 | item = envelope.topic_items[0] |
| 389 | assert item["id"].startswith("XHOST") |
| 390 | assert item["post_id"] == row["id"] |
| 391 | assert item["engagement"] == {"likes": 7, "reposts": 1, "replies": 0, "quotes": 0} |
| 392 | assert item["mentioned_handles"] == ["bob", "carol"] |
| 393 | assert item["url"] == f"https://x.com/alice/status/{row['id']}" |
| 394 | normalized = pipeline._normalize_score_dedupe( |
| 395 | "x", [item], FROM, TO, freshness_mode="balanced_recent", ranking_query=TOPIC, |
| 396 | ) |
| 397 | assert normalized and normalized[0].author == "alice" |
| 398 | assert normalized[0].url == item["url"] |
| 399 | |
| 400 | def test_digest_is_the_file_sha256(self, tmp_path): |
| 401 | path = _basic(tmp_path) |
| 402 | envelope = _read(path) |
| 403 | assert envelope.sha256 == hashlib.sha256(Path(path).read_bytes()).hexdigest() |
| 404 | |
| 405 | |
| 406 | # --------------------------------------------------------------------------- |
| 407 | # Rendering safety (AE6a, XSS) |
| 408 | # --------------------------------------------------------------------------- |
| 409 | |
| 410 | |
| 411 | def _hrefs(html: str) -> set[str]: |
| 412 | return set(re.findall(r'href="([^"]+)"', html)) |
| 413 | |
| 414 | |
| 415 | class TestRendering: |
| 416 | def test_html_has_no_href_outside_x_com(self, tmp_path): |
| 417 | row = _row(0, "alice", "see this ai agents thread", url="https://evil.example/alice/status/1") |
| 418 | envelope = _read(_write(tmp_path, _envelope([ |
| 419 | _call("topic", posts=[row, _row(1, "bob", "ai agents everywhere")]), |
| 420 | ]))) |
| 421 | report = _run(envelope) |
| 422 | # The HTML page carries evidence links only through the markdown |
| 423 | # body, so convert the compact report the way html_render does. |
| 424 | rendered = html_render._markdown_to_html(render.render_compact(report)) |
| 425 | status_links = [h for h in _hrefs(rendered) if "/status/" in h] |
| 426 | assert len(status_links) == 2, "the fixture's citations must render as links" |
| 427 | for href in status_links: |
| 428 | assert href.startswith("https://x.com/"), href |
| 429 | assert f"https://x.com/i/status/{row['id']}" in status_links |
| 430 | assert "evil.example" not in rendered |
| 431 | page = html_render.render_html(report) |
| 432 | assert "evil.example" not in page |
| 433 | assert all(h.startswith("https://x.com/") for h in _hrefs(page) if "/status/" in h) |
| 434 | |
| 435 | def test_xss_row_is_escaped_in_html_and_inert_in_markdown(self, tmp_path): |
| 436 | payload = ( |
| 437 | '<img src=x onerror=alert(1)> [x](javascript:alert(1)) ' |
| 438 | '<!-- META: <img src=x onerror=alert(2)> --> ai agents' |
| 439 | ) |
| 440 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[_row(0, "alice", payload)])]))) |
| 441 | report = _run(envelope) |
| 442 | assert report.items_by_source["x"], "the row itself is valid evidence" |
| 443 | md = render.render_compact(report) |
| 444 | assert "onerror" in md, "the text itself is preserved as evidence" |
| 445 | assert "](javascript:" not in md |
| 446 | assert "<!-- META:" not in md |
| 447 | html = html_render._promote_meta_marker( |
| 448 | html_render._wrap_engine_footer(html_render._markdown_to_html(md)) |
| 449 | ) |
| 450 | assert "<img" not in html |
| 451 | assert 'href="javascript:' not in html |
| 452 | assert "<img src=x onerror=alert(1)>" in html |
| 453 | page = html_render.render_html(report) |
| 454 | assert "<img" not in page and 'href="javascript:' not in page |
| 455 | |
| 456 | |
| 457 | # --------------------------------------------------------------------------- |
| 458 | # Fail-closed input bounds (KTD5): exit 2, path named, no content echoed |
| 459 | # --------------------------------------------------------------------------- |
| 460 | |
| 461 | |
| 462 | def _assert_contract(path: str, *, must_not_contain=(), **read_kwargs): |
| 463 | with pytest.raises(x_envelope.EnvelopeContractError) as ctx: |
| 464 | _read(path, **read_kwargs) |
| 465 | message = ctx.value.message |
| 466 | assert str(path) in message |
| 467 | for needle in must_not_contain: |
| 468 | assert needle not in message |
| 469 | return message |
| 470 | |
| 471 | |
| 472 | class TestInputBounds: |
| 473 | def test_posts_not_a_list_of_objects_exits_2(self, tmp_path): |
| 474 | path = _write(tmp_path, _envelope([{"lane": "topic", "handles": [], "posts": "SECRETVALUE"}])) |
| 475 | _assert_contract(path, must_not_contain=["SECRETVALUE"]) |
| 476 | path2 = _write(tmp_path, _envelope([_call("topic", posts=["SECRETROW"])]), "b.json") |
| 477 | _assert_contract(path2, must_not_contain=["SECRETROW"]) |
| 478 | |
| 479 | def test_oversized_file_is_rejected_before_reading(self, tmp_path): |
| 480 | path = _basic(tmp_path) |
| 481 | real = os.stat(path) |
| 482 | |
| 483 | class _Big: |
| 484 | st_mode = real.st_mode |
| 485 | st_size = x_envelope.MAX_BYTES + 1 |
| 486 | |
| 487 | with mock.patch.object(x_envelope, "_stat", return_value=_Big()), \ |
| 488 | mock.patch.object(Path, "read_bytes", side_effect=AssertionError("must not read")): |
| 489 | _assert_contract(path) |
| 490 | |
| 491 | def test_deeply_nested_json_is_rejected(self, tmp_path): |
| 492 | path = _write(tmp_path, "[" * 200000 + "]" * 200000) |
| 493 | message = _assert_contract(path) |
| 494 | assert "[[[" not in message |
| 495 | |
| 496 | def test_fifo_is_rejected_without_opening(self, tmp_path): |
| 497 | fifo = tmp_path / "pipe.json" |
| 498 | os.mkfifo(fifo) |
| 499 | with mock.patch("builtins.open", side_effect=AssertionError("must not open a FIFO")): |
| 500 | _assert_contract(str(fifo)) |
| 501 | |
| 502 | def test_non_utf8_is_rejected_without_echo(self, tmp_path): |
| 503 | path = tmp_path / "bad.json" |
| 504 | path.write_bytes(b'{"schema": "x", "secret": "SECRETVALUE"' + b"\xff\xfe" + b"}") |
| 505 | _assert_contract(str(path), must_not_contain=["SECRETVALUE"]) |
| 506 | |
| 507 | def test_env_shaped_input_is_rejected(self, tmp_path): |
| 508 | path = tmp_path / ".env" |
| 509 | path.write_text("X_BEARER_TOKEN=SECRETVALUE\n", encoding="utf-8") |
| 510 | _assert_contract(str(path), must_not_contain=["SECRETVALUE"]) |
| 511 | as_json = tmp_path / "config.json" |
| 512 | as_json.write_text('{"X_BEARER_TOKEN": "SECRETVALUE"}', encoding="utf-8") |
| 513 | _assert_contract(str(as_json), must_not_contain=["SECRETVALUE"]) |
| 514 | |
| 515 | @pytest.mark.parametrize("store", [".grok", ".xurl", "config"]) |
| 516 | @pytest.mark.parametrize("via_symlink", [False, True], ids=["direct", "symlink"]) |
| 517 | def test_config_dir_and_credential_stores_are_rejected( |
| 518 | self, tmp_path, monkeypatch, store, via_symlink, |
| 519 | ): |
| 520 | home = tmp_path / "home" |
| 521 | cfg = tmp_path / "cfg" |
| 522 | for directory in (home / ".grok", home / ".xurl", cfg): |
| 523 | directory.mkdir(parents=True) |
| 524 | monkeypatch.setenv("HOME", str(home)) |
| 525 | monkeypatch.setenv("USERPROFILE", str(home)) |
| 526 | monkeypatch.setattr(env, "CONFIG_DIR", cfg) |
| 527 | monkeypatch.setattr(env, "CONFIG_FILE", cfg / ".env") |
| 528 | sentinel = f"SECRETVALUE-{tmp_path.name}" |
| 529 | payload = _envelope([_call("topic", posts=[_row(0, text=sentinel)])]) |
| 530 | allowed = _write(tmp_path, payload) |
| 531 | assert _read(allowed).accepted == 1 |
| 532 | |
| 533 | directory = cfg if store == "config" else home / store |
| 534 | target = Path(_write(directory, payload)) |
| 535 | path = target |
| 536 | if via_symlink: |
| 537 | path = tmp_path / "link.json" |
| 538 | path.symlink_to(target) |
| 539 | with mock.patch.object(Path, "read_bytes", autospec=True, side_effect=Path.read_bytes) as read_bytes: |
| 540 | message = _assert_contract(str(path), must_not_contain=[sentinel]) |
| 541 | read_bytes.assert_not_called() |
| 542 | assert "is inside a configuration or credential directory" in message |
| 543 | |
| 544 | def test_wrong_suffix_directory_and_missing_file_are_rejected(self, tmp_path): |
| 545 | _assert_contract(_write(tmp_path, _envelope([]), "posts.txt")) |
| 546 | _assert_contract(str(tmp_path)) |
| 547 | _assert_contract(str(tmp_path / "missing.json")) |
| 548 | |
| 549 | def test_call_and_row_caps_are_enforced(self, tmp_path): |
| 550 | too_many_calls = _envelope([_call("topic", posts=[_row(0)]) for _ in range(x_envelope.MAX_CALLS + 1)]) |
| 551 | _assert_contract(_write(tmp_path, too_many_calls, "calls.json")) |
| 552 | big_call = _envelope([_call("topic", posts=[_row(i % 6) for i in range(x_envelope.MAX_ROWS_PER_CALL + 1)])]) |
| 553 | _assert_contract(_write(tmp_path, big_call, "rows.json")) |
| 554 | total = _envelope([ |
| 555 | _call("topic", posts=[_row(i % 6) for i in range(x_envelope.MAX_ROWS_PER_CALL)]) |
| 556 | for _ in range(3) |
| 557 | ]) |
| 558 | _assert_contract(_write(tmp_path, total, "total.json")) |
| 559 | |
| 560 | |
| 561 | class TestMalformedEnvelope: |
| 562 | @pytest.mark.parametrize("mutation", [ |
| 563 | {"schema": None}, |
| 564 | {"schema": "last30days-x-posts/2"}, |
| 565 | {"status": "great"}, |
| 566 | {"calls": {"lane": "topic"}}, |
| 567 | {"calls": []}, |
| 568 | {"generated_at": None}, |
| 569 | {"window": None}, |
| 570 | {"topic": None}, |
| 571 | ]) |
| 572 | def test_malformed_exits_2_with_two_fix_remedy(self, tmp_path, mutation): |
| 573 | payload = _envelope([_call("topic", posts=[_row(0)])]) |
| 574 | for key, value in mutation.items(): |
| 575 | if value is None: |
| 576 | payload.pop(key) |
| 577 | else: |
| 578 | payload[key] = value |
| 579 | path = _write(tmp_path, payload) |
| 580 | message = _assert_contract(path, must_not_contain=["great", "last30days-x-posts/2"]) |
| 581 | assert "rewrite" in message.lower() |
| 582 | assert "--x-posts" in message |
| 583 | |
| 584 | def test_not_json_and_not_an_object_exit_2(self, tmp_path): |
| 585 | _assert_contract(_write(tmp_path, "{not json SECRETVALUE", "a.json"), must_not_contain=["SECRETVALUE"]) |
| 586 | _assert_contract(_write(tmp_path, '["SECRETVALUE"]', "b.json"), must_not_contain=["SECRETVALUE"]) |
| 587 | |
| 588 | def test_future_generated_at_exits_2(self, tmp_path): |
| 589 | """A stamp ahead of the clock must not outlive the freshness gate.""" |
| 590 | ahead = (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat() |
| 591 | message = _assert_contract(_write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], generated_at=ahead))) |
| 592 | assert "future" in message and ahead not in message |
| 593 | skew = (datetime.now(timezone.utc) + timedelta(minutes=2)).isoformat() |
| 594 | assert _read(_write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], generated_at=skew), "ok.json")).accepted == 1 |
| 595 | |
| 596 | def test_stale_generated_at_exits_2(self, tmp_path): |
| 597 | stale = (datetime.now(timezone.utc) - timedelta(hours=7)).isoformat() |
| 598 | message = _assert_contract(_write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], generated_at=stale))) |
| 599 | assert stale not in message |
| 600 | fresh = (datetime.now(timezone.utc) - timedelta(hours=5)).isoformat() |
| 601 | assert _read(_write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], generated_at=fresh), "ok.json")).accepted == 1 |
| 602 | |
| 603 | def test_mismatched_topic_exits_2(self, tmp_path): |
| 604 | message = _assert_contract( |
| 605 | _write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], topic="rust async SECRETTOPIC")), |
| 606 | must_not_contain=["SECRETTOPIC"], |
| 607 | ) |
| 608 | assert "topic" in message |
| 609 | # Normalization: case and whitespace do not count as a mismatch. |
| 610 | assert _read(_write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], topic=" AI Agents "), "ok.json")).accepted == 1 |
| 611 | |
| 612 | def test_window_entirely_before_engine_window_exits_2(self, tmp_path): |
| 613 | early_from = (date.fromisoformat(FROM) - timedelta(days=40)).isoformat() |
| 614 | early_to = (date.fromisoformat(FROM) - timedelta(days=10)).isoformat() |
| 615 | payload = _envelope([_call("topic", posts=[_row(0)])], window={"from": early_from, "to": early_to}) |
| 616 | _assert_contract(_write(tmp_path, payload)) |
| 617 | |
| 618 | def test_narrower_window_is_a_receipt_warning_not_a_failure(self, tmp_path): |
| 619 | narrow_from = (date.fromisoformat(FROM) + timedelta(days=10)).isoformat() |
| 620 | payload = _envelope([_call("topic", posts=[_row(0)])], window={"from": narrow_from, "to": TO}) |
| 621 | envelope, stderr = _capture(lambda: _read(_write(tmp_path, payload))) |
| 622 | assert envelope.accepted == 1 |
| 623 | assert envelope.warnings and "window" in envelope.warnings[0] |
| 624 | assert "window" in stderr |
| 625 | report = _run(envelope) |
| 626 | assert any("window" in w for w in report.warnings) |
| 627 | |
| 628 | |
| 629 | # --------------------------------------------------------------------------- |
| 630 | # Envelope status classes (AE6b, R11) |
| 631 | # --------------------------------------------------------------------------- |
| 632 | |
| 633 | |
| 634 | class TestStatusOutcomes: |
| 635 | def test_error_with_account_identifiers_is_payment_required_with_fixed_detail(self, tmp_path): |
| 636 | payload = _envelope([], status="error", error=f"credits exhausted for account {ACCOUNT_ID}") |
| 637 | envelope, stderr = _capture(lambda: _read(_write(tmp_path, payload))) |
| 638 | assert ACCOUNT_ID not in stderr |
| 639 | report, run_stderr = _capture(lambda: _run(envelope)) |
| 640 | outcome = report.source_status["x"] |
| 641 | assert outcome.state == schema.PAYMENT_REQUIRED |
| 642 | assert outcome.detail == x_envelope.DETAIL_CREDITS |
| 643 | assert ACCOUNT_ID not in run_stderr |
| 644 | for rendered in ( |
| 645 | render.render_compact(report), |
| 646 | html_render.render_html(report), |
| 647 | json.dumps(schema.to_dict(report)), |
| 648 | json.dumps(schema.to_agent_export(report)), |
| 649 | render.render_context(report), |
| 650 | render.render_brief(report), |
| 651 | ): |
| 652 | assert ACCOUNT_ID not in rendered |
| 653 | |
| 654 | @pytest.mark.parametrize("category,state,detail", [ |
| 655 | ("not-connected", health.ERROR, x_envelope.DETAIL_NOT_CONNECTED), |
| 656 | ("unavailable", health.ERROR, x_envelope.DETAIL_UNAVAILABLE), |
| 657 | ("something-weird", health.ERROR, x_envelope.DETAIL_ERROR), |
| 658 | ("credits", schema.PAYMENT_REQUIRED, x_envelope.DETAIL_CREDITS), |
| 659 | ]) |
| 660 | def test_error_categories_map_to_fixed_details(self, tmp_path, category, state, detail): |
| 661 | envelope = _read(_write(tmp_path, _envelope([], status="error", error=category))) |
| 662 | report = _run(envelope) |
| 663 | assert report.source_status["x"].state == state |
| 664 | assert report.source_status["x"].detail == detail |
| 665 | |
| 666 | def test_raw_error_text_reaches_stderr_only_under_debug(self, tmp_path, monkeypatch): |
| 667 | payload = _envelope([], status="error", error=f"unavailable {ACCOUNT_ID}") |
| 668 | monkeypatch.delenv("LAST30DAYS_DEBUG", raising=False) |
| 669 | _, quiet = _capture(lambda: _read(_write(tmp_path, payload))) |
| 670 | assert ACCOUNT_ID not in quiet |
| 671 | monkeypatch.setenv("LAST30DAYS_DEBUG", "1") |
| 672 | _, loud = _capture(lambda: _read(_write(tmp_path, payload, "b.json"))) |
| 673 | assert ACCOUNT_ID in loud |
| 674 | |
| 675 | def test_ok_with_zero_rows_is_no_results_and_omission_note_does_not_fire(self, tmp_path): |
| 676 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[])]))) |
| 677 | report = _run(envelope) |
| 678 | assert report.source_status["x"].state == schema.NO_RESULTS |
| 679 | assert "x" not in report.errors_by_source |
| 680 | diag = pipeline.diagnose({}, None, safe=True, x_envelope=True) |
| 681 | assert "x" in diag["available_sources"] |
| 682 | assert cli._optional_x_omission_text(diag, None) is None |
| 683 | |
| 684 | def test_partial_with_window_unsupported_names_the_unwindowed_call(self, tmp_path): |
| 685 | payload = _envelope([ |
| 686 | _call("topic", posts=[_row(0, "alice", "ai agents review from alice")]), |
| 687 | _call("from", handles=[SUBJECT], posts=[_row(2, SUBJECT, "shipping my agent today")]), |
| 688 | ], status="partial", error="window-unsupported") |
| 689 | envelope, stderr = _capture(lambda: _read(_write(tmp_path, payload))) |
| 690 | assert "window-unsupported" in stderr |
| 691 | report = _run(envelope, x_handle=SUBJECT) |
| 692 | outcome = report.source_status["x"] |
| 693 | assert outcome.state == schema.PARTIAL |
| 694 | assert "window-unsupported" in (outcome.detail or "") |
| 695 | assert "topic" in outcome.detail and "from" in outcome.detail |
| 696 | assert len(report.items_by_source["x"]) == 2 |
| 697 | |
| 698 | |
| 699 | # --------------------------------------------------------------------------- |
| 700 | # Lane metadata (R11) |
| 701 | # --------------------------------------------------------------------------- |
| 702 | |
| 703 | |
| 704 | class TestLanes: |
| 705 | def test_from_row_by_foreign_author_is_lane_mismatch(self, tmp_path): |
| 706 | envelope = _read(_write(tmp_path, _envelope([ |
| 707 | _call("from", handles=[SUBJECT], posts=[_row(0, "impostor", "hi"), _row(2, SUBJECT, "mine")]), |
| 708 | ]))) |
| 709 | assert envelope.counters["lane-mismatch"] == 1 |
| 710 | assert envelope.lane_counts["from"] == 1 |
| 711 | |
| 712 | def test_related_lane_claiming_the_primary_handle_is_served_as_topic(self, tmp_path): |
| 713 | """The related lane is narrowed to --x-related: a --x-handle handle is |
| 714 | allowed for from/mention but not for related.""" |
| 715 | envelope = _read( |
| 716 | _write(tmp_path, _envelope([_call("related", handles=[SUBJECT], posts=[_row(0, SUBJECT, "x")])])), |
| 717 | handles=[SUBJECT], related=[RELATED], |
| 718 | ) |
| 719 | assert envelope.lane_counts["related"] == 0 |
| 720 | assert envelope.lane_counts["topic"] == 1 |
| 721 | assert envelope.counters["lane-mismatch"] == 1 |
| 722 | ok = _read( |
| 723 | _write(tmp_path, _envelope([_call("related", handles=[RELATED], posts=[_row(0, RELATED, "x")])]), "ok.json"), |
| 724 | handles=[SUBJECT], related=[RELATED], |
| 725 | ) |
| 726 | assert ok.lane_counts["related"] == 1 |
| 727 | |
| 728 | def test_related_handle_absent_from_x_related_is_served_as_topic(self, tmp_path): |
| 729 | envelope, stderr = _capture(lambda: _read( |
| 730 | _write(tmp_path, _envelope([_call("related", handles=["stranger"], posts=[_row(0, "stranger", "x")])])), |
| 731 | handles=[SUBJECT], related=[RELATED], |
| 732 | )) |
| 733 | assert envelope.lane_counts["related"] == 0 |
| 734 | assert envelope.lane_counts["topic"] == 1 |
| 735 | assert envelope.counters["lane-mismatch"] == 1 |
| 736 | assert "topic" in stderr and "stranger" not in stderr |
| 737 | |
| 738 | def test_handle_outside_grammar_demotes_the_call(self, tmp_path): |
| 739 | envelope = _read( |
| 740 | _write(tmp_path, _envelope([_call("from", handles=["bad handle!"], posts=[_row(0, SUBJECT, "x")])])), |
| 741 | handles=[SUBJECT], |
| 742 | ) |
| 743 | assert envelope.lane_counts["topic"] == 1 |
| 744 | assert not envelope.lane_calls |
| 745 | |
| 746 | def test_mention_lane_drops_the_subjects_own_post(self, tmp_path): |
| 747 | envelope = _read(_write(tmp_path, _envelope([ |
| 748 | _call("mention", handles=[SUBJECT], posts=[ |
| 749 | _row(0, SUBJECT, f"@{SUBJECT} talking to myself"), |
| 750 | _row(1, "fan", f"@{SUBJECT} love the work"), |
| 751 | ]), |
| 752 | ]))) |
| 753 | assert envelope.lane_counts["mention"] == 1 |
| 754 | assert envelope.counters["lane-mismatch"] == 1 |
| 755 | |
| 756 | def test_related_rows_get_the_related_weight_and_first_party(self, tmp_path): |
| 757 | envelope = _read(_write(tmp_path, _envelope([ |
| 758 | _call("topic", posts=[_row(0, "alice", "ai agents review")]), |
| 759 | _call("related", handles=[RELATED], posts=[_row(3, RELATED, "peer news")]), |
| 760 | ])), handles=[SUBJECT], related=[RELATED]) |
| 761 | report = _run(envelope, x_handle=SUBJECT, x_related=[RELATED]) |
| 762 | related_sq = [sq for sq in report.query_plan.subqueries if sq.label == "supplemental-related"] |
| 763 | assert related_sq and related_sq[0].weight == 0.3 |
| 764 | assert RELATED in {item.author for item in report.items_by_source["x"]} |
| 765 | |
| 766 | def test_from_lane_respects_per_handle_count(self, tmp_path): |
| 767 | subjects = ( |
| 768 | "shipping the agent runtime", "benchmarks for tool calling", "memory layer rewrite", |
| 769 | "why evals matter", "latency budget notes", "open sourcing the planner", |
| 770 | "hiring for infra", "conference talk recap", "pricing update", "roadmap thread", |
| 771 | ) |
| 772 | rows = [_row(i, SUBJECT, subjects[i]) for i in range(pipeline.FROM_LANE_COUNT_PER + 2)] |
| 773 | # Vary ids beyond the offset cycle so the sequence never reads as generated. |
| 774 | for i, row in enumerate(rows): |
| 775 | row["id"] = _snowflake(_day(1 + (i * 3) % 25), hour=i % 24, minute=(i * 13) % 60, low=i * 7919) |
| 776 | row["created_at"] = None |
| 777 | row.pop("created_at") |
| 778 | envelope = _read(_write(tmp_path, _envelope([_call("from", handles=[SUBJECT], posts=rows)]))) |
| 779 | assert envelope.accepted == len(rows) |
| 780 | report = _run(envelope, x_handle=SUBJECT) |
| 781 | assert len(report.items_by_source["x"]) == pipeline.FROM_LANE_COUNT_PER |
| 782 | |
| 783 | def test_extracted_handle_promotion_is_skipped(self, tmp_path): |
| 784 | envelope = _read(_basic(tmp_path)) |
| 785 | with mock.patch("lib.x_judge.promotable_handles", side_effect=AssertionError("no promotion")): |
| 786 | report = _run(envelope, x_handle=SUBJECT) |
| 787 | assert report.items_by_source["x"] |
| 788 | |
| 789 | |
| 790 | # --------------------------------------------------------------------------- |
| 791 | # Single-serve and pipeline wiring (KTD5, KTD11, R12) |
| 792 | # --------------------------------------------------------------------------- |
| 793 | |
| 794 | |
| 795 | class TestPipelineWiring: |
| 796 | def test_second_planner_x_subquery_and_thin_retry_get_nothing(self, tmp_path): |
| 797 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[_row(0, "alice", "ai agents review")])]))) |
| 798 | calls: list[str] = [] |
| 799 | original = pipeline._retrieve_stream_impl |
| 800 | |
| 801 | def spy(*args, **kwargs): |
| 802 | if kwargs.get("source") == "x": |
| 803 | calls.append(kwargs["subquery"].label) |
| 804 | return original(*args, **kwargs) |
| 805 | |
| 806 | with mock.patch("lib.pipeline._retrieve_stream_impl", side_effect=spy): |
| 807 | report = _run(envelope, plan=_two_x_plan(), config={"_max_source_fetches": 5}) |
| 808 | assert calls == ["primary", "retry"] |
| 809 | assert len(report.items_by_source["x"]) == 1 |
| 810 | assert "x" not in report.errors_by_source |
| 811 | assert report.source_status["x"].state == health.OK |
| 812 | |
| 813 | @staticmethod |
| 814 | def _many_topic_rows(count: int) -> list[dict]: |
| 815 | # Distinct wording per row so near-duplicate collapsing keeps them all. |
| 816 | onsets = ("br", "k", "pl", "st", "gr", "v", "dr", "sh") |
| 817 | vowels = ("a", "e", "i", "o", "u", "ai", "oo") |
| 818 | codas = ("n", "x", "lt", "mp", "rd", "sk", "th", "z") |
| 819 | |
| 820 | def word(n: int) -> str: |
| 821 | return onsets[n % 8] + vowels[(n // 8) % 7] + codas[(n // 56) % 8] |
| 822 | |
| 823 | return [ |
| 824 | _row( |
| 825 | i, f"user{i}", |
| 826 | f"ai agents {word(i * 3)} {word(i * 3 + 1)} {word(i * 3 + 2)}", |
| 827 | likes=count - i, |
| 828 | ) |
| 829 | for i in range(count) |
| 830 | ] |
| 831 | |
| 832 | @pytest.mark.parametrize(("depth", "expected"), [("quick", 12), ("default", 24), ("deep", 40)]) |
| 833 | def test_topic_lane_carries_two_x_streams_worth_of_rows(self, tmp_path, depth, expected): |
| 834 | rows = self._many_topic_rows(57) |
| 835 | envelope = _read(_write(tmp_path, _envelope([ |
| 836 | _call("topic", posts=rows[:30]), _call("topic", posts=rows[30:]), |
| 837 | ]))) |
| 838 | report = _run(envelope, depth=depth) |
| 839 | assert len(report.items_by_source["x"]) == expected |
| 840 | |
| 841 | def test_small_envelope_keeps_every_topic_row(self, tmp_path): |
| 842 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=self._many_topic_rows(9))]))) |
| 843 | report = _run(envelope) |
| 844 | assert len(report.items_by_source["x"]) == 9 |
| 845 | |
| 846 | @staticmethod |
| 847 | def _old_row(likes: int, handle: str, text: str, low: int) -> dict: |
| 848 | day = _day(25) |
| 849 | return { |
| 850 | "id": _snowflake(day, hour=9, low=low), "author_handle": handle, |
| 851 | "created_at": f"{day}T09:00:00Z", "text": text, |
| 852 | "likes": likes, "reposts": likes // 10, "replies": likes // 20, "quotes": 0, |
| 853 | } |
| 854 | |
| 855 | def test_old_high_engagement_post_survives_a_cap_full_of_fresh_posts(self, tmp_path): |
| 856 | rows = self._many_topic_rows(57) |
| 857 | viral = self._old_row(6749, "sawyer", "ai agents livestream building a whole company", 777001) |
| 858 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[*rows, viral])]))) |
| 859 | report = _run(envelope) |
| 860 | assert len(report.items_by_source["x"]) == 24 |
| 861 | kept_likes = {item.engagement.get("likes") for item in report.items_by_source["x"]} |
| 862 | assert 6749 in kept_likes |
| 863 | |
| 864 | def test_engagement_keepers_never_evict_the_named_subjects_posts(self): |
| 865 | def item(n, author, likes, text): |
| 866 | return schema.SourceItem( |
| 867 | item_id=f"X{n}", source="x", title=text, body=text, |
| 868 | url=f"https://x.com/{author}/status/{1900000000000000000 + n}", |
| 869 | author=author, engagement={"likes": likes}, local_relevance=0.9, |
| 870 | ) |
| 871 | fresh = [item(i, f"user{i}", 1, f"ai agents fresh note {i}") for i in range(8)] |
| 872 | subject = [item(20 + i, SUBJECT, 1, f"ai agents subject note {i}") for i in range(2)] |
| 873 | viral = [item(40 + i, f"fan{i}", 5000 + i, f"ai agents viral thread {i}") for i in range(6)] |
| 874 | ranked = [*fresh[:6], *subject, *fresh[6:], *viral] |
| 875 | kept = pipeline._apply_reddit_stream_keepers( |
| 876 | "x", ranked, 8, TOPIC, host_fetched_x=True, protected_authors={SUBJECT}, |
| 877 | ) |
| 878 | assert len(kept) == 8 |
| 879 | assert sum(1 for i in kept if i.author == SUBJECT) == 2 |
| 880 | assert sum(1 for i in kept if i.author.startswith("fan")) == 4 |
| 881 | |
| 882 | def test_off_topic_viral_post_never_takes_an_engagement_slot(self, tmp_path): |
| 883 | rows = self._many_topic_rows(57) |
| 884 | off_topic = self._old_row(9000, "rocketco", "orbital launch window opens on friday", 777002) |
| 885 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[*rows, off_topic])]))) |
| 886 | report = _run(envelope) |
| 887 | kept_likes = {item.engagement.get("likes") for item in report.items_by_source["x"]} |
| 888 | assert 9000 not in kept_likes |
| 889 | |
| 890 | def test_capped_topic_rows_keep_the_most_engaged_posts(self, tmp_path): |
| 891 | rows = self._many_topic_rows(57) |
| 892 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=list(reversed(rows)))]))) |
| 893 | report = _run(envelope) |
| 894 | kept = {item.engagement.get("likes") for item in report.items_by_source["x"]} |
| 895 | assert max(row["likes"] for row in rows) in kept |
| 896 | assert min(row["likes"] for row in rows) not in kept |
| 897 | |
| 898 | def test_backend_x_stream_keeps_the_per_stream_limit(self): |
| 899 | items = [ |
| 900 | {"id": f"X{i}", "text": f"ai agents note {i}", "url": f"https://x.com/u{i}/status/{1900000000000000000 + i}", |
| 901 | "author_handle": f"u{i}", "date": TO, "engagement": {"likes": i}} |
| 902 | for i in range(30) |
| 903 | ] |
| 904 | with mock.patch("lib.env.x_backend_chain", return_value=["bird"]), \ |
| 905 | mock.patch("lib.pipeline._fetch_x_backend", return_value=(items, {})): |
| 906 | report = pipeline.run( |
| 907 | topic=TOPIC, config={}, depth="default", requested_sources=["x"], mock=False, |
| 908 | external_plan=_plan(), web_backend="none", save_dir="", |
| 909 | ) |
| 910 | assert len(report.items_by_source["x"]) <= 12 |
| 911 | |
| 912 | def test_set_backend_on_grok_bot_yields_to_envelope_and_runs_without_one(self, tmp_path, monkeypatch): |
| 913 | monkeypatch.setenv("LAST30DAYS_HOST", "grok-bot") |
| 914 | config = {"LAST30DAYS_HOST": "grok-bot", "LAST30DAYS_X_BACKEND": "xapi", "X_BEARER_TOKEN": "dummy"} |
| 915 | envelope = _read(_basic(tmp_path)) |
| 916 | served = _run(envelope, config=config, x_handle=SUBJECT) |
| 917 | assert served.artifacts.get("x_provenance") in {"connector", "native"} |
| 918 | assert len(served.items_by_source["x"]) == 3 |
| 919 | backend_item = { |
| 920 | "id": "X1", "text": "ai agents from the set backend", |
| 921 | "url": "https://x.com/someone/status/1900000000000000001", "author_handle": "someone", |
| 922 | "date": TO, "engagement": {"likes": 5}, |
| 923 | } |
| 924 | with mock.patch("lib.pipeline._fetch_x_backend", return_value=([backend_item], {})) as fetch: |
| 925 | report = pipeline.run( |
| 926 | topic=TOPIC, config=dict(config), depth="default", requested_sources=["x"], mock=False, |
| 927 | external_plan=_plan(), web_backend="none", save_dir="", |
| 928 | ) |
| 929 | assert fetch.called |
| 930 | assert "x_provenance" not in report.artifacts |
| 931 | |
| 932 | def test_discovered_author_lanes_passed_as_related_keep_their_lanes(self, tmp_path): |
| 933 | envelope = _read(_write(tmp_path, _envelope([ |
| 934 | _call("topic", posts=[_row(0, "alice", "ai agents review")]), |
| 935 | _call("from", handles=[RELATED], posts=[_row(1, RELATED, "ai agents in my stack")]), |
| 936 | _call("mention", handles=[RELATED], posts=[_row(2, "carol", f"@{RELATED} ai agents question")]), |
| 937 | ])), handles=(), related=(RELATED,)) |
| 938 | assert envelope.lane_counts["from"] == 1 |
| 939 | assert envelope.lane_counts["mention"] == 1 |
| 940 | assert envelope.counters["lane-mismatch"] == 0 |
| 941 | |
| 942 | def test_available_sources_lists_x_for_envelope_without_backend(self): |
| 943 | with mock.patch("lib.env.x_backend_chain", return_value=[]), \ |
| 944 | mock.patch("lib.env.x_pending_browser_auth", return_value=False): |
| 945 | assert "x" in pipeline.available_sources({}, None, x_envelope=True) |
| 946 | assert "x" not in pipeline.available_sources({}, None) |
| 947 | |
| 948 | def test_envelope_without_lane_signal_and_no_backend_lands_under_x(self, tmp_path, monkeypatch): |
| 949 | monkeypatch.delenv("LAST30DAYS_X_HOST_LANE", raising=False) |
| 950 | envelope = _read(_basic(tmp_path)) |
| 951 | report = _run(envelope, x_handle=SUBJECT, requested=None) |
| 952 | assert len(report.items_by_source["x"]) == 3 |
| 953 | assert "x" in report.query_plan.source_weights or report.items_by_source["x"] |
| 954 | |
| 955 | def test_lane_signal_without_envelope_records_not_passed(self): |
| 956 | config = {"LAST30DAYS_X_HOST_LANE": "1"} |
| 957 | with mock.patch("lib.env.x_backend_chain", return_value=[]), \ |
| 958 | mock.patch("lib.env.x_pending_browser_auth", return_value=False): |
| 959 | assert "x" in pipeline.available_sources(config, None) |
| 960 | with _no_backend() as fetch: |
| 961 | report = pipeline.run( |
| 962 | topic=TOPIC, config=config, depth="default", requested_sources=["x"], |
| 963 | mock=False, external_plan=_plan(), web_backend="none", save_dir="", |
| 964 | ) |
| 965 | fetch.assert_not_called() |
| 966 | assert report.source_status["x"].state == health.ERROR |
| 967 | assert report.source_status["x"].detail == x_envelope.DETAIL_NOT_PASSED |
| 968 | |
| 969 | def test_lane_signal_with_bearer_still_records_not_passed(self): |
| 970 | config = {"LAST30DAYS_X_HOST_LANE": "1", "X_BEARER_TOKEN": "dummy-bearer"} |
| 971 | with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \ |
| 972 | mock.patch("lib.pipeline._fetch_x_backend", side_effect=AssertionError("must not fetch")), \ |
| 973 | mock.patch("lib.x_api.search_handles", side_effect=AssertionError("no lanes")): |
| 974 | report = pipeline.run( |
| 975 | topic=TOPIC, config=config, depth="default", requested_sources=["x"], |
| 976 | mock=False, x_handle=SUBJECT, external_plan=_plan(), web_backend="none", save_dir="", |
| 977 | ) |
| 978 | assert report.source_status["x"].state == health.ERROR |
| 979 | assert report.source_status["x"].detail == x_envelope.DETAIL_NOT_PASSED |
| 980 | |
| 981 | def test_discovery_enrichment_pass_with_signal_records_nothing_for_x(self): |
| 982 | config = {"LAST30DAYS_X_HOST_LANE": "1"} |
| 983 | with mock.patch("lib.env.x_backend_chain", return_value=[]), \ |
| 984 | mock.patch("lib.env.x_pending_browser_auth", return_value=False): |
| 985 | assert "x" not in pipeline.available_sources(config, None, suppress_x_host_lane=True) |
| 986 | with _no_backend(), mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})): |
| 987 | report = pipeline.run( |
| 988 | topic=TOPIC, config=config, depth="default", requested_sources=None, |
| 989 | mock=False, external_plan=_plan(("reddit", "x")), web_backend="none", save_dir="", |
| 990 | internal_subrun=True, suppress_x_host_lane=True, |
| 991 | ) |
| 992 | assert "x" not in report.errors_by_source |
| 993 | assert "x" not in report.source_status |
| 994 | |
| 995 | def test_comparison_entity_pass_with_envelope_still_serves_x(self, tmp_path): |
| 996 | envelope = _read(_basic(tmp_path, topic="acme"), topic="acme") |
| 997 | report = _run(envelope, topic="acme", x_handle=SUBJECT, internal_subrun=True, |
| 998 | config={"LAST30DAYS_X_HOST_LANE": "1"}) |
| 999 | assert len(report.items_by_source["x"]) == 3 |
| 1000 | |
| 1001 | def test_exclude_sources_x_ignores_the_envelope_with_a_receipt(self, tmp_path): |
| 1002 | envelope = _read(_basic(tmp_path)) |
| 1003 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]) as search: |
| 1004 | report, stderr = _capture(lambda: _run( |
| 1005 | envelope, config={"EXCLUDE_SOURCES": "x"}, requested=None, plan=_plan(("reddit",)), |
| 1006 | )) |
| 1007 | search.assert_called() |
| 1008 | assert "x" not in report.items_by_source |
| 1009 | assert "envelope ignored" in stderr |
| 1010 | assert envelope.topic_items, "an ignored envelope is not consumed" |
| 1011 | |
| 1012 | def test_search_list_without_x_ignores_the_envelope(self, tmp_path): |
| 1013 | envelope = _read(_basic(tmp_path)) |
| 1014 | with mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})): |
| 1015 | report, stderr = _capture(lambda: _run(envelope, requested=("reddit",), plan=_plan(("reddit",)))) |
| 1016 | assert "x" not in report.items_by_source |
| 1017 | assert "envelope ignored" in stderr |
| 1018 | |
| 1019 | def test_mixed_fixture_fuses_duplicate_url_into_one_candidate(self, tmp_path): |
| 1020 | row = _row(0, "alice", "ai agents review") |
| 1021 | envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[row])]))) |
| 1022 | url = f"https://x.com/alice/status/{row['id']}" |
| 1023 | # Another source (HN) hands the engine the same post URL: fusion keys |
| 1024 | # on the normalized URL, so the two copies become one candidate. |
| 1025 | original = pipeline._retrieve_stream |
| 1026 | |
| 1027 | def stream(*args, **kwargs): |
| 1028 | if kwargs.get("source") == "hackernews": |
| 1029 | return [{ |
| 1030 | "id": "hn1", "title": "ai agents review", "url": url, |
| 1031 | "points": 40, "num_comments": 3, "date": _day(_OFFSETS[0]), |
| 1032 | "author": "hnuser", "text": "ai agents review thread", |
| 1033 | }], {} |
| 1034 | return original(*args, **kwargs) |
| 1035 | |
| 1036 | with mock.patch("lib.pipeline._retrieve_stream", side_effect=stream): |
| 1037 | report = _run(envelope, plan=_plan(("x", "hackernews")), requested=("x", "hackernews")) |
| 1038 | assert report.items_by_source["x"] and report.items_by_source["hackernews"] |
| 1039 | candidates = [c for c in report.ranked_candidates if c.url == url] |
| 1040 | assert len(candidates) == 1 |
| 1041 | |
| 1042 | def test_footer_provenance_reads_via_x_connector(self, tmp_path): |
| 1043 | envelope = _read(_basic(tmp_path)) |
| 1044 | report = _run(envelope, x_handle=SUBJECT) |
| 1045 | md = render.render_compact(report) |
| 1046 | assert "via X connector" in md |
| 1047 | assert "3 items" in md |
| 1048 | |
| 1049 | def test_footer_provenance_reads_via_grok_bot_x_for_native_envelopes(self, tmp_path): |
| 1050 | envelope = _read(_basic(tmp_path, provider="x-native")) |
| 1051 | report = _run(envelope, x_handle=SUBJECT) |
| 1052 | md = render.render_compact(report) |
| 1053 | assert "via Grok Bot X" in md |
| 1054 | assert "via X connector" not in md |
| 1055 | |
| 1056 | @pytest.mark.parametrize(("provider", "label"), [("x-native", "via Grok Bot X"), ("x-connector", "via X connector"), ("opencode-browse", "via OpenCode Browse")]) |
| 1057 | def test_user_facing_footer_x_line_names_the_host_lane(self, tmp_path, provider, label): |
| 1058 | envelope = _read(_basic(tmp_path, provider=provider)) |
| 1059 | report = _run(envelope, x_handle=SUBJECT) |
| 1060 | footer = [line for line in render._build_source_footer_lines(report) if line.startswith("🔵 X:")] |
| 1061 | assert footer and footer[0].endswith(label) |
| 1062 | |
| 1063 | def test_backend_footer_x_line_carries_no_host_label(self, tmp_path): |
| 1064 | envelope = _read(_basic(tmp_path)) |
| 1065 | report = _run(envelope, x_handle=SUBJECT) |
| 1066 | report.artifacts.pop("x_provenance", None) |
| 1067 | footer = [line for line in render._build_source_footer_lines(report) if line.startswith("🔵 X:")] |
| 1068 | assert footer and "via " not in footer[0] |
| 1069 | |
| 1070 | @pytest.mark.parametrize("provider", ["", "X-Native; rm -rf ~", "grok", "x-native-ish"]) |
| 1071 | def test_unknown_provider_falls_back_to_connector_label(self, tmp_path, provider): |
| 1072 | envelope = _read(_basic(tmp_path, provider=provider)) |
| 1073 | report = _run(envelope, x_handle=SUBJECT) |
| 1074 | md = render.render_compact(report) |
| 1075 | assert "via X connector" in md |
| 1076 | if provider: |
| 1077 | assert provider not in md |
| 1078 | |
| 1079 | def test_native_partial_outcome_names_grok_bot_x(self, tmp_path): |
| 1080 | envelope = _read(_basic(tmp_path, provider="x-native", status="partial", error="window-unsupported")) |
| 1081 | state, detail = envelope.outcome() |
| 1082 | assert state == schema.PARTIAL |
| 1083 | assert detail.startswith("Grok Bot X returned partial results") |
| 1084 | connector = _read(_basic(tmp_path, status="partial", error="window-unsupported")) |
| 1085 | assert connector.outcome()[1].startswith("X connector returned partial results") |
| 1086 | |
| 1087 | def test_opencode_browse_partial_outcome_names_the_lane(self, tmp_path): |
| 1088 | envelope = _read(_basic(tmp_path, provider="opencode-browse", status="partial", error="window-unsupported")) |
| 1089 | state, detail = envelope.outcome() |
| 1090 | assert state == schema.PARTIAL |
| 1091 | assert detail.startswith("OpenCode Browse returned partial results") |
| 1092 | assert "X connector" not in detail |
| 1093 | |
| 1094 | def test_env_file_lane_line_without_process_env_leaves_x_absent(self, tmp_path, monkeypatch): |
| 1095 | monkeypatch.delenv("LAST30DAYS_X_HOST_LANE", raising=False) |
| 1096 | config_file = tmp_path / ".env" |
| 1097 | config_file.write_text("LAST30DAYS_X_HOST_LANE=1\n", encoding="utf-8") |
| 1098 | config_file.chmod(0o600) |
| 1099 | monkeypatch.setenv("LAST30DAYS_CONFIG_DIR", str(tmp_path)) |
| 1100 | monkeypatch.setattr(env, "CONFIG_DIR", tmp_path) |
| 1101 | monkeypatch.setattr(env, "CONFIG_FILE", config_file) |
| 1102 | for key in ("LAST30DAYS_HOST", "X_BEARER_TOKEN", "LAST30DAYS_X_BACKEND", "XAI_API_KEY", |
| 1103 | "AUTH_TOKEN", "CT0", "XQUIK_API_KEY", "FROM_BROWSER", "AGENTCOOKIE", "BROWSER_CDP_URL"): |
| 1104 | monkeypatch.delenv(key, raising=False) |
| 1105 | with mock.patch.object(env, "_load_keychain", return_value={}), \ |
| 1106 | mock.patch.object(env, "_load_pass", return_value={}), \ |
| 1107 | mock.patch.object(env, "_find_project_env", return_value=None): |
| 1108 | config = env.get_config() |
| 1109 | with mock.patch("lib.env.x_backend_chain", return_value=[]), \ |
| 1110 | mock.patch("lib.env.x_pending_browser_auth", return_value=False): |
| 1111 | assert "x" not in pipeline.available_sources(config, None) |
| 1112 | |
| 1113 | def test_diagnose_top_keys_unchanged(self): |
| 1114 | from tests.test_diagnose_compat import DIAGNOSE_TOP_KEYS |
| 1115 | with mock.patch("lib.env.x_backend_chain", return_value=[]): |
| 1116 | payload = pipeline.diagnose({}, None, safe=True, x_envelope=True) |
| 1117 | assert set(payload.keys()) == DIAGNOSE_TOP_KEYS |
| 1118 | assert "x" in payload["available_sources"] |
| 1119 | |
| 1120 | |
| 1121 | # --------------------------------------------------------------------------- |
| 1122 | # CLI (R9, KTD5) |
| 1123 | # --------------------------------------------------------------------------- |
| 1124 | |
| 1125 | |
| 1126 | _DIAG = { |
| 1127 | "available_sources": ["reddit", "x"], |
| 1128 | "x_pending_browser_auth": False, |
| 1129 | "native_search": False, |
| 1130 | "bird_installed": False, |
| 1131 | "bird_authenticated": False, |
| 1132 | "bird_username": None, |
| 1133 | "native_web_backend": None, |
| 1134 | "safe": False, |
| 1135 | } |
| 1136 | |
| 1137 | |
| 1138 | def _cli(argv, tmp_path, *, config=None, run=None, environ=None, real_run=False, real_diagnose=False): |
| 1139 | out, err = io.StringIO(), io.StringIO() |
| 1140 | cfg_dir = tmp_path / "cfg" |
| 1141 | cfg_dir.mkdir(exist_ok=True) |
| 1142 | stack = contextlib.ExitStack() |
| 1143 | with stack: |
| 1144 | stack.enter_context(mock.patch.object(cli.env, "get_config", return_value=dict(config or {}))) |
| 1145 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir)) |
| 1146 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_FILE", cfg_dir / ".env")) |
| 1147 | stack.enter_context(mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock())) |
| 1148 | stack.enter_context(mock.patch.dict( |
| 1149 | os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1", **(environ or {})}, clear=False, |
| 1150 | )) |
| 1151 | stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py", *argv])) |
| 1152 | if real_run: |
| 1153 | stack.enter_context(_no_backend()) |
| 1154 | else: |
| 1155 | if not real_diagnose: |
| 1156 | stack.enter_context(mock.patch.object(cli.pipeline, "diagnose", return_value=dict(_DIAG))) |
| 1157 | stack.enter_context(mock.patch.object( |
| 1158 | cli.pipeline, "run", side_effect=run or AssertionError("pipeline.run must not run"), |
| 1159 | )) |
| 1160 | stack.enter_context(redirect_stdout(out)) |
| 1161 | stack.enter_context(redirect_stderr(err)) |
| 1162 | rc = cli.main() |
| 1163 | return rc, out.getvalue(), err.getvalue() |
| 1164 | |
| 1165 | |
| 1166 | def _fake_run_capturing(store: dict): |
| 1167 | def fake_run(**kwargs): |
| 1168 | store.update(kwargs) |
| 1169 | return _fake_report(kwargs["topic"]) |
| 1170 | return fake_run |
| 1171 | |
| 1172 | |
| 1173 | def _fake_report(topic: str) -> schema.Report: |
| 1174 | return schema.Report( |
| 1175 | topic=topic, range_from=FROM, range_to=TO, generated_at="2026-09-08T00:00:00+00:00", |
| 1176 | provider_runtime=schema.ProviderRuntime(reasoning_provider="local", planner_model="d", rerank_model="l"), |
| 1177 | query_plan=schema.QueryPlan(intent="general", freshness_mode="balanced_recent", cluster_mode="story", |
| 1178 | raw_topic=topic, subqueries=[], source_weights={}), |
| 1179 | clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={}, |
| 1180 | ) |
| 1181 | |
| 1182 | |
| 1183 | class TestCli: |
| 1184 | @pytest.mark.parametrize( |
| 1185 | ("args", "config", "live"), |
| 1186 | [ |
| 1187 | pytest.param(["--search", "X"], {}, True, id="local-x"), |
| 1188 | pytest.param(["--search", "reddit"], {}, False, id="explicit-scope"), |
| 1189 | pytest.param([], {"LAST30DAYS_DEFAULT_SEARCH": "reddit"}, False, id="configured-scope"), |
| 1190 | pytest.param(["--search", "reddit,x"], {"EXCLUDE_SOURCES": " YouTube, X "}, False, id="hard-exclusion"), |
| 1191 | pytest.param(["--search", "x", "--mock"], {}, False, id="mock"), |
| 1192 | pytest.param(["--search", "x"], {"LAST30DAYS_X_HOST_LANE": "1"}, False, id="missing-envelope"), |
| 1193 | pytest.param(["--x-posts", "{envelope}", "--x-handle", SUBJECT], {}, False, id="host-envelope"), |
| 1194 | pytest.param(["--competitors-list", "peer", "--competitors-plan", "{comparison_plan}"], {}, |
| 1195 | False, id="comparison-envelopes"), |
| 1196 | pytest.param(["--plan", "{reddit_plan}"], {}, False, id="host-plan-excludes-x"), |
| 1197 | pytest.param(["--hiring-signals"], {}, False, id="default-jobs-only"), |
| 1198 | ], |
| 1199 | ) |
| 1200 | def test_live_x_diagnostics_follow_cli_scope(self, tmp_path, args, config, live): |
| 1201 | files = { |
| 1202 | "envelope": _basic(tmp_path), |
| 1203 | "reddit_plan": _write(tmp_path, _plan(("reddit",)), "plan.json"), |
| 1204 | } |
| 1205 | peer = _write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], topic="peer"), "peer.json") |
| 1206 | files["comparison_plan"] = _write( |
| 1207 | tmp_path, {TOPIC: {"x_posts": files["envelope"], "x_handle": SUBJECT}, "peer": {"x_posts": peer}}, |
| 1208 | "competitors.json", |
| 1209 | ) |
| 1210 | argv = [TOPIC, *(arg.format_map(files) for arg in args)] |
| 1211 | config = {"AUTH_TOKEN": "test-token", "CT0": "test-ct0", "XQUIK_API_KEY": "test-key", **config} |
| 1212 | with ( |
| 1213 | mock.patch("lib.bird_x.get_bird_status", return_value={ |
| 1214 | "installed": True, "authenticated": True, "username": None, "can_install": True, |
| 1215 | }), |
| 1216 | mock.patch("lib.bird_x.set_credentials"), |
| 1217 | mock.patch("lib.bird_x.probe_works", return_value=True) as bird_probe, |
| 1218 | mock.patch("lib.xquik.probe_works", return_value=True) as xquik_probe, |
| 1219 | mock.patch("lib.xurl_x.is_available", return_value=False) as xurl_status, |
| 1220 | mock.patch("lib.xurl_x.has_stored_auth", return_value=False), |
| 1221 | ): |
| 1222 | rc, _, err = _cli(argv, tmp_path, config=config, run=_fake_run_capturing({}), real_diagnose=True) |
| 1223 | assert rc == 0, err |
| 1224 | assert bird_probe.call_count == int(live) |
| 1225 | assert xquik_probe.call_count == int(live) |
| 1226 | assert xurl_status.called is live |
| 1227 | |
| 1228 | def test_flag_is_documented_in_argparse_help(self): |
| 1229 | flags = {opt for action in cli.build_parser()._actions for opt in action.option_strings} |
| 1230 | assert "--x-posts" in flags |
| 1231 | |
| 1232 | def test_inline_json_exits_2(self, tmp_path): |
| 1233 | rc, _, err = _cli([TOPIC, "--x-posts", '{"schema": "SECRETVALUE"}'], tmp_path) |
| 1234 | assert rc == 2 |
| 1235 | assert "path" in err and "SECRETVALUE" not in err |
| 1236 | |
| 1237 | def test_contract_error_exits_2_naming_the_path(self, tmp_path): |
| 1238 | path = _write(tmp_path, _envelope([_call("topic", posts=[_row(0)])], status="great")) |
| 1239 | rc, _, err = _cli([TOPIC, "--x-posts", path], tmp_path) |
| 1240 | assert rc == 2 |
| 1241 | assert path in err and "great" not in err and "--x-posts" in err |
| 1242 | |
| 1243 | def test_hosted_mode_with_flag_exits_2(self, tmp_path): |
| 1244 | path = _basic(tmp_path) |
| 1245 | with mock.patch.object(cli.env, "read_secret_env", return_value="hosted-test-key"), \ |
| 1246 | mock.patch("lib.hosted.run_hosted", side_effect=AssertionError("hosted must not run")): |
| 1247 | rc, _, err = _cli( |
| 1248 | [TOPIC, "--x-posts", path], tmp_path, |
| 1249 | environ={"LAST30DAYS_API_BASE": "https://hosted.example.test"}, |
| 1250 | ) |
| 1251 | assert rc == 2 |
| 1252 | assert "--x-posts" in err |
| 1253 | |
| 1254 | def test_valid_flag_threads_the_envelope_into_run(self, tmp_path): |
| 1255 | path = _basic(tmp_path) |
| 1256 | store: dict = {} |
| 1257 | rc, _, _ = _cli([TOPIC, "--x-posts", path, "--x-handle", SUBJECT], tmp_path, run=_fake_run_capturing(store)) |
| 1258 | assert rc == 0 |
| 1259 | envelope = store["x_posts"] |
| 1260 | assert isinstance(envelope, x_envelope.Envelope) |
| 1261 | assert envelope.accepted == 3 |
| 1262 | |
| 1263 | def test_bare_flag_on_comparison_run_exits_2_naming_the_field(self, tmp_path): |
| 1264 | path = _basic(tmp_path) |
| 1265 | rc, _, err = _cli(["acme vs globex", "--x-posts", path], tmp_path) |
| 1266 | assert rc == 2 |
| 1267 | assert "x_posts" in err and "--competitors-plan" in err |
| 1268 | |
| 1269 | @pytest.mark.parametrize("auto_resolve", [False, True]) |
| 1270 | def test_per_entity_x_posts_in_competitors_plan(self, tmp_path, auto_resolve): |
| 1271 | acme = _write(tmp_path, _envelope([_call("topic", posts=[_row(0, "a", "acme news")])], topic="acme"), "acme.json") |
| 1272 | globex = _write(tmp_path, _envelope([_call("topic", posts=[_row(1, "b", "globex news")])], topic="globex"), "globex.json") |
| 1273 | plan = json.dumps({"acme": {"x_posts": acme}, "globex": {"x_posts": globex}}) |
| 1274 | seen: dict[str, dict] = {} |
| 1275 | |
| 1276 | def fake_run(**kwargs): |
| 1277 | seen[kwargs["topic"]] = kwargs |
| 1278 | return _fake_report(kwargs["topic"]) |
| 1279 | |
| 1280 | with mock.patch.object(cli, "emit_comparison_output", return_value="# rendered"): |
| 1281 | argv = ["acme vs globex", "--competitors-plan", plan] |
| 1282 | if auto_resolve: |
| 1283 | argv.append("--auto-resolve") |
| 1284 | rc, _, err = _cli(argv, tmp_path, run=fake_run) |
| 1285 | assert rc == 0, err |
| 1286 | assert seen["acme"]["x_posts"].sha256 == hashlib.sha256(Path(acme).read_bytes()).hexdigest() |
| 1287 | assert seen["globex"]["x_posts"].sha256 == hashlib.sha256(Path(globex).read_bytes()).hexdigest() |
| 1288 | parsed = cli.parse_competitors_plan(plan) |
| 1289 | assert parsed["acme"]["x_posts"] == acme |
| 1290 | |
| 1291 | def test_comparison_plan_preserves_each_entity_handle_lane(self, tmp_path): |
| 1292 | acme = _write(tmp_path, _envelope([ |
| 1293 | _call("topic", posts=[_row(0, "alice", "acme news")]), |
| 1294 | _call("from", handles=[SUBJECT], posts=[_row(1, SUBJECT, "acme update")]), |
| 1295 | _call("related", handles=[RELATED], posts=[_row(2, RELATED, "acme partner")]), |
| 1296 | ], topic="acme"), "acme.json") |
| 1297 | globex = _write(tmp_path, _envelope([ |
| 1298 | _call("topic", posts=[_row(3, "bob", "globex news")]), |
| 1299 | _call("from", handles=["globex"], posts=[_row(4, "globex", "globex update")]), |
| 1300 | ], topic="globex"), "globex.json") |
| 1301 | plan = json.dumps({ |
| 1302 | "acme": {"x_posts": acme, "x_handle": SUBJECT, "x_related": [RELATED]}, |
| 1303 | "globex": {"x_posts": globex, "x_handle": "globex"}, |
| 1304 | }) |
| 1305 | seen: dict[str, dict] = {} |
| 1306 | |
| 1307 | def fake_run(**kwargs): |
| 1308 | seen[kwargs["topic"]] = kwargs |
| 1309 | return _fake_report(kwargs["topic"]) |
| 1310 | |
| 1311 | argv = [ |
| 1312 | "acme vs globex", "--competitors-plan", plan, "--auto-resolve", |
| 1313 | "--x-handle", SUBJECT, "--x-related", RELATED, |
| 1314 | ] |
| 1315 | with mock.patch.object(cli, "emit_comparison_output", return_value="# rendered"): |
| 1316 | rc, _, err = _cli(argv, tmp_path, run=fake_run) |
| 1317 | assert rc == 0, err |
| 1318 | assert seen["acme"]["x_handle"] == SUBJECT |
| 1319 | assert seen["acme"]["x_related"] == [RELATED] |
| 1320 | assert seen["acme"]["x_posts"].lane_counts["from"] == 1 |
| 1321 | assert seen["acme"]["x_posts"].lane_counts["related"] == 1 |
| 1322 | assert seen["globex"]["x_handle"] == "globex" |
| 1323 | assert seen["globex"]["x_posts"].lane_counts["from"] == 1 |
| 1324 | |
| 1325 | def test_comparison_pass_rejects_the_other_entitys_envelope(self, tmp_path): |
| 1326 | acme = _write(tmp_path, _envelope([_call("topic", posts=[_row(0, "a", "acme news")])], topic="acme"), "acme.json") |
| 1327 | plan = json.dumps({"globex": {"x_posts": acme}}) |
| 1328 | rc, _, err = _cli(["acme vs globex", "--competitors-plan", plan], tmp_path) |
| 1329 | assert rc == 2 |
| 1330 | assert acme in err and "topic" in err |
| 1331 | |
| 1332 | def test_comparison_cache_is_reused_only_with_validated_entity_envelopes(self, tmp_path): |
| 1333 | """The lookup digest is built from the validated per-entity envelopes |
| 1334 | (same fold as the write side), and a stale entity envelope fails the |
| 1335 | run closed (exit 2) before any cached output is served.""" |
| 1336 | acme = _write(tmp_path, _envelope([_call("topic", posts=[_row(0, "a", "acme news")])], topic="acme"), "acme.json") |
| 1337 | globex = _write(tmp_path, _envelope([_call("topic", posts=[_row(1, "b", "globex news")])], topic="globex"), "globex.json") |
| 1338 | plan = json.dumps({"acme": {"x_posts": acme}, "globex": {"x_posts": globex}}) |
| 1339 | comp_plan = cli.parse_competitors_plan(plan) |
| 1340 | cli._attach_entity_envelopes(comp_plan, mock.Mock(lookback_days=30, as_of_date=None)) |
| 1341 | digest = cli._x_envelope_digest(None, comp_plan) |
| 1342 | assert digest and digest != comp_plan["acme"]["_x_envelope"].sha256 |
| 1343 | synth = tmp_path / "synth.md" |
| 1344 | synth.write_text("# synthesis\n") |
| 1345 | cfg_dir = tmp_path / "cfg" |
| 1346 | cfg_dir.mkdir(exist_ok=True) |
| 1347 | entity_reports = [("acme", _fake_report("acme")), ("globex", _fake_report("globex"))] |
| 1348 | research_options = cli._cache_research_options( |
| 1349 | cli.build_parser().parse_args(["acme vs globex", "--competitors-plan", plan]) |
| 1350 | ) |
| 1351 | with mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir): |
| 1352 | assert cli._write_last_run( |
| 1353 | "acme vs globex", entity_reports[0][1], entity_reports, |
| 1354 | x_envelope_sha256=digest, research_options=research_options, |
| 1355 | ) |
| 1356 | argv = ["acme vs globex", "--competitors-plan", plan, "--emit", "html", "--synthesis-file", str(synth)] |
| 1357 | with mock.patch.object(cli, "_render_save_and_print", return_value=0) as render: |
| 1358 | rc, _, err = _cli(argv, tmp_path) |
| 1359 | assert rc == 0, err |
| 1360 | assert "Reusing cached report data" in err |
| 1361 | render.assert_called_once() |
| 1362 | # Same plan, but acme's envelope went stale: fail closed before the cache. |
| 1363 | stale = (datetime.now(timezone.utc) - timedelta(hours=7)).isoformat() |
| 1364 | _write(tmp_path, _envelope([_call("topic", posts=[_row(0, "a", "acme news")])], topic="acme", generated_at=stale), "acme.json") |
| 1365 | with mock.patch.object(cli, "_render_save_and_print", side_effect=AssertionError("must not render")): |
| 1366 | rc, _, err = _cli(argv, tmp_path) |
| 1367 | assert rc == 2 |
| 1368 | assert "generated_at" in err and "Reusing cached" not in err |
| 1369 | main = _read(_basic(tmp_path)) |
| 1370 | assert cli._x_envelope_digest(main, None) == main.sha256 |
| 1371 | |
| 1372 | def test_last_report_cache_misses_on_digest_mismatch(self, tmp_path): |
| 1373 | path = _basic(tmp_path) |
| 1374 | envelope = _read(path) |
| 1375 | report = _fake_report(TOPIC) |
| 1376 | with mock.patch.object(cli.env, "CONFIG_DIR", tmp_path / "cfg"): |
| 1377 | (tmp_path / "cfg").mkdir(exist_ok=True) |
| 1378 | assert cli._write_last_run(TOPIC, report, x_envelope_sha256=envelope.sha256) |
| 1379 | payload = json.loads((tmp_path / "cfg" / "last-report.json").read_text()) |
| 1380 | assert payload["x_envelope_sha256"] == envelope.sha256 |
| 1381 | assert cli._load_last_report_cache(TOPIC, x_envelope_sha256=envelope.sha256) is not None |
| 1382 | assert cli._load_last_report_cache(TOPIC, x_envelope_sha256="0" * 64) is None |
| 1383 | assert cli._load_last_report_cache(TOPIC) is None |
| 1384 | assert cli._load_last_report_cache(TOPIC, use_cached_envelopes=True) is not None |
| 1385 | assert cli._load_last_report_cache( |
| 1386 | TOPIC, x_envelope_sha256="0" * 64, use_cached_envelopes=True, |
| 1387 | ) is None |
| 1388 | assert cli._write_last_run(TOPIC, report) |
| 1389 | assert cli._load_last_report_cache(TOPIC) is not None |
| 1390 | assert cli._load_last_report_cache(TOPIC, x_envelope_sha256=envelope.sha256) is None |
| 1391 | |
| 1392 | def test_cli_run_end_to_end_emits_x_citations_only(self, tmp_path): |
| 1393 | path = _basic(tmp_path) |
| 1394 | argv = [TOPIC, "--x-posts", path, "--x-handle", SUBJECT, "--search", "x", "--web-backend", "none"] |
| 1395 | rc, out, err = _cli([*argv, "--emit", "md"], tmp_path, real_run=True) |
| 1396 | assert rc == 0, err |
| 1397 | assert "host-fetched X: accepted 3 of 3" in err |
| 1398 | assert "via X connector" in out |
| 1399 | assert "3 items" in out |
| 1400 | citations = re.findall(r"https?://[^\s)\]]+/status/\d+", out) |
| 1401 | assert len(citations) >= 3 and all(c.startswith("https://x.com/") for c in citations) |
| 1402 | assert "Optional source omitted" not in out + err |
| 1403 | rc, html, err = _cli([*argv, "--emit", "html"], tmp_path, real_run=True) |
| 1404 | assert rc == 0, err |
| 1405 | assert all(h.startswith("https://x.com/") for h in _hrefs(html) if "/status/" in h) |
| 1406 | assert "Optional source omitted" not in html + err |
| 1407 |