| 1 | """Host-fetched X envelope: the ``--x-posts`` lane. |
| 2 | |
| 3 | The hosting model fetches posts through its own X connector and writes them |
| 4 | to a ``.json`` file of flat rows. The engine ingests that file as its X |
| 5 | source for one run: strict at the envelope level (a malformed, stale, or |
| 6 | off-topic file fails closed with an exit-2 contract error), lenient per row |
| 7 | (a bad row is dropped and counted), and trusting nothing a row asserts about |
| 8 | itself beyond a numeric id and a grammar-valid handle. |
| 9 | |
| 10 | Shape (``schema: "last30days-x-posts/1"``):: |
| 11 | |
| 12 | { |
| 13 | "schema": "last30days-x-posts/1", |
| 14 | "generated_at": "<ISO-8601>", |
| 15 | "topic": "<the run topic>", |
| 16 | "window": {"from": "YYYY-MM-DD", "to": "YYYY-MM-DD"}, |
| 17 | "provider": "<free text>", |
| 18 | "status": "ok" | "partial" | "error", |
| 19 | "error": "<short category: credits | not-connected | unavailable | window-unsupported>", |
| 20 | "calls": [{"lane": "topic|from|mention|related", "handles": [...], "posts": [ROW, ...]}] |
| 21 | } |
| 22 | |
| 23 | A ROW is a flat object with exactly ``id``, ``author_handle``, ``created_at``, |
| 24 | ``text``, ``likes``, ``reposts``, ``replies``, ``quotes``. Any other key is |
| 25 | ignored (and counted once per row as ``extra-fields``); in particular a |
| 26 | row-supplied ``url`` is never used for the citation, only cross-checked. |
| 27 | |
| 28 | The envelope is single-serve: the first X subquery takes the topic-lane rows |
| 29 | and the handle-lane section takes the lane calls; later X subqueries, |
| 30 | judge-retry, and thin-retry get nothing (``take_topic`` / ``take_lanes`` |
| 31 | return ``None`` once consumed). |
| 32 | |
| 33 | Security contract: contract errors name the path and the field, never a |
| 34 | field value; the envelope's raw ``error`` text reaches stderr only under |
| 35 | ``LAST30DAYS_DEBUG``; every outcome detail is one of the fixed strings below. |
| 36 | """ |
| 37 | |
| 38 | from __future__ import annotations |
| 39 | |
| 40 | import hashlib |
| 41 | import html |
| 42 | import json |
| 43 | import math |
| 44 | import os |
| 45 | import re |
| 46 | import stat |
| 47 | import threading |
| 48 | from dataclasses import dataclass, field |
| 49 | from datetime import date, datetime, timedelta, timezone |
| 50 | from pathlib import Path |
| 51 | from typing import Any |
| 52 | |
| 53 | from . import env, health, log, schema |
| 54 | from .relevance import token_overlap_relevance as _compute_relevance |
| 55 | from .query import leading_mentions |
| 56 | from .x_api import _clean_handle, _decode_snowflake, _looks_generated, is_own_post |
| 57 | |
| 58 | SCHEMA = "last30days-x-posts/1" |
| 59 | ID_PREFIX = "XHOST" |
| 60 | |
| 61 | # Input bounds. Named so the recipe and the receipts can quote them. |
| 62 | MAX_BYTES = 8 * 1024 * 1024 |
| 63 | MAX_CALLS = 20 |
| 64 | MAX_ROWS_PER_CALL = 500 |
| 65 | MAX_ROWS_TOTAL = 1000 |
| 66 | MAX_TEXT_CHARS = 10_000 |
| 67 | MAX_AGE_SECONDS = 6 * 60 * 60 |
| 68 | MAX_ID_DIGITS = 20 |
| 69 | # Realistic upper bound for engagement counts so huge JSON integers cannot |
| 70 | # overflow float conversion during downstream ranking (signals.log1p_safe). |
| 71 | MAX_ENGAGEMENT_COUNT = 1_000_000_000_000 |
| 72 | |
| 73 | LANES = ("topic", "from", "mention", "related") |
| 74 | STATUSES = ("ok", "partial", "error") |
| 75 | ROW_FIELDS = frozenset( |
| 76 | {"id", "author_handle", "created_at", "text", "likes", "reposts", "replies", "quotes"} |
| 77 | ) |
| 78 | COUNTERS = ( |
| 79 | "out-of-window", |
| 80 | "missing-id-text", |
| 81 | "uncitable", |
| 82 | "date-mismatch", |
| 83 | "handle-mismatch", |
| 84 | "duplicate", |
| 85 | "lane-mismatch", |
| 86 | "truncated", |
| 87 | "extra-fields", |
| 88 | ) |
| 89 | |
| 90 | # Engine-authored fixed outcome details. The envelope's own error text |
| 91 | # never becomes a detail string. |
| 92 | _CONNECTOR_LABEL = "X connector" |
| 93 | _NATIVE_LABEL = "Grok Bot X" |
| 94 | _BROWSE_LABEL = "OpenCode Browse" |
| 95 | DETAIL_CREDITS = f"{_CONNECTOR_LABEL} reported no credits" |
| 96 | DETAIL_NOT_CONNECTED = f"{_CONNECTOR_LABEL} not connected" |
| 97 | DETAIL_UNAVAILABLE = f"{_CONNECTOR_LABEL} unavailable" |
| 98 | DETAIL_ERROR = f"{_CONNECTOR_LABEL} error" |
| 99 | DETAIL_GENERATED = f"{_CONNECTOR_LABEL} rows rejected (id sequence looks generated)" |
| 100 | DETAIL_PARTIAL = f"{_CONNECTOR_LABEL} returned partial results" |
| 101 | DETAIL_NOT_PASSED = "connector result not passed" |
| 102 | |
| 103 | # The envelope's free-text ``provider`` reaches output only through this |
| 104 | # allowlist: ``x-native`` (Grok Bot's built-in X tools) and ``opencode-browse`` |
| 105 | # (OpenCode's paired browse MCP) get their own labels, and anything else keeps |
| 106 | # the connector wording. |
| 107 | PROVIDER_NATIVE = "x-native" |
| 108 | PROVIDER_OPENCODE_BROWSE = "opencode-browse" |
| 109 | PROVENANCE_NATIVE = "native" |
| 110 | PROVENANCE_OPENCODE_BROWSE = "opencode-browse" |
| 111 | PROVENANCE_CONNECTOR = "connector" |
| 112 | PROVENANCE_LABELS = { |
| 113 | PROVENANCE_CONNECTOR: _CONNECTOR_LABEL, |
| 114 | PROVENANCE_NATIVE: _NATIVE_LABEL, |
| 115 | PROVENANCE_OPENCODE_BROWSE: _BROWSE_LABEL, |
| 116 | } |
| 117 | |
| 118 | CATEGORY_CREDITS = "credits" |
| 119 | CATEGORY_NOT_CONNECTED = "not-connected" |
| 120 | CATEGORY_UNAVAILABLE = "unavailable" |
| 121 | CATEGORY_WINDOW_UNSUPPORTED = "window-unsupported" |
| 122 | _ALLOWED_ERROR_CATEGORIES = frozenset({ |
| 123 | CATEGORY_CREDITS, |
| 124 | CATEGORY_NOT_CONNECTED, |
| 125 | CATEGORY_UNAVAILABLE, |
| 126 | CATEGORY_WINDOW_UNSUPPORTED, |
| 127 | }) |
| 128 | _CATEGORY_GENERATED = "generated" |
| 129 | |
| 130 | _REMEDY = ( |
| 131 | "Rewrite the file to the last30days-x-posts/1 shape, or re-run without --x-posts." |
| 132 | ) |
| 133 | |
| 134 | # Directories the envelope must never be read from: the engine's own config |
| 135 | # dir (which holds .env) and the credential stores of the X tooling and the |
| 136 | # usual shell neighbours. Checked after realpath so a symlink cannot reach in. |
| 137 | _CREDENTIAL_STORES = ( |
| 138 | "~/.xurl", |
| 139 | "~/.grok", |
| 140 | "~/.config/last30days", |
| 141 | "~/.config/gh", |
| 142 | "~/.aws", |
| 143 | "~/.ssh", |
| 144 | "~/.netrc", |
| 145 | ) |
| 146 | |
| 147 | # Snowflake ids predate nothing before X's epoch; a decode outside |
| 148 | # [2010-11-04, now + 1 day] is not a real post id. |
| 149 | _SNOWFLAKE_FLOOR = datetime(2010, 11, 4, tzinfo=timezone.utc) |
| 150 | |
| 151 | # C0 and C1 control characters. Text keeps newlines and tabs; handles and the |
| 152 | # error field keep nothing. |
| 153 | _CONTROL_ANY_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]") |
| 154 | _CONTROL_TEXT_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") |
| 155 | _PLACEHOLDER_HANDLES = frozenset( |
| 156 | {"unknown", "n/a", "na", "none", "null", "user", "anonymous", "placeholder", "handle"} |
| 157 | ) |
| 158 | _STATUS_URL_RE = re.compile( |
| 159 | r"^https?://(?:www\.|mobile\.)?(?:x\.com|twitter\.com)/(?P<handle>[A-Za-z0-9_]{1,15})/status(?:es)?/(?P<id>\d+)", |
| 160 | re.IGNORECASE, |
| 161 | ) |
| 162 | _TOPIC_STRIP = "\"'“”‘’ \t" |
| 163 | |
| 164 | |
| 165 | class EnvelopeContractError(Exception): |
| 166 | """The envelope failed its contract: unreadable, out of bounds, malformed, |
| 167 | stale, off-topic, or outside the research window. The CLI maps this to |
| 168 | exit code 2. The message names the path and the offending field only.""" |
| 169 | |
| 170 | def __init__(self, message: str) -> None: |
| 171 | super().__init__(message) |
| 172 | self.message = message |
| 173 | |
| 174 | |
| 175 | @dataclass |
| 176 | class EnvelopeCall: |
| 177 | """One validated handle-lane call (``from``, ``mention``, or ``related``).""" |
| 178 | |
| 179 | index: int |
| 180 | lane: str |
| 181 | handles: list[str] |
| 182 | posts: list[dict[str, Any]] |
| 183 | |
| 184 | |
| 185 | @dataclass |
| 186 | class Envelope: |
| 187 | """A validated ``--x-posts`` file, ready to be served once.""" |
| 188 | |
| 189 | path: str |
| 190 | sha256: str |
| 191 | status: str |
| 192 | error_category: str |
| 193 | provider: str |
| 194 | window: tuple[str, str] |
| 195 | topic_items: list[dict[str, Any]] |
| 196 | lane_calls: list[EnvelopeCall] |
| 197 | counters: dict[str, int] |
| 198 | accepted: int |
| 199 | total: int |
| 200 | lane_counts: dict[str, int] |
| 201 | call_lanes: list[str] |
| 202 | warnings: list[str] = field(default_factory=list) |
| 203 | notes: list[str] = field(default_factory=list) |
| 204 | _lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False) |
| 205 | _topic_served: bool = field(default=False, repr=False, compare=False) |
| 206 | _lanes_served: bool = field(default=False, repr=False, compare=False) |
| 207 | |
| 208 | def take_topic(self) -> list[dict[str, Any]] | None: |
| 209 | """Topic-lane rows on the first call; ``None`` once consumed.""" |
| 210 | with self._lock: |
| 211 | if self._topic_served: |
| 212 | return None |
| 213 | self._topic_served = True |
| 214 | return list(self.topic_items) |
| 215 | |
| 216 | def take_lanes(self) -> list[EnvelopeCall] | None: |
| 217 | """Handle-lane calls on the first call; ``None`` once consumed.""" |
| 218 | with self._lock: |
| 219 | if self._lanes_served: |
| 220 | return None |
| 221 | self._lanes_served = True |
| 222 | return list(self.lane_calls) |
| 223 | |
| 224 | @property |
| 225 | def provenance(self) -> str: |
| 226 | """``native`` / ``opencode-browse`` for a named host lane, else ``connector``.""" |
| 227 | provider = self.provider.lower() |
| 228 | if provider == PROVIDER_NATIVE: |
| 229 | return PROVENANCE_NATIVE |
| 230 | if provider == PROVIDER_OPENCODE_BROWSE: |
| 231 | return PROVENANCE_OPENCODE_BROWSE |
| 232 | return PROVENANCE_CONNECTOR |
| 233 | |
| 234 | def outcome(self) -> tuple[schema.RunOutcomeState, str] | None: |
| 235 | """The fixed source outcome for a non-ok envelope, else ``None``.""" |
| 236 | if self.status == "error": |
| 237 | state, detail = _error_outcome(self.error_category) |
| 238 | return state, self._labelled(detail) |
| 239 | if self.status == "partial": |
| 240 | detail = DETAIL_PARTIAL |
| 241 | if self.error_category: |
| 242 | detail += f": {self.error_category}" |
| 243 | if self.call_lanes: |
| 244 | detail += f" (calls: {', '.join(self.call_lanes)})" |
| 245 | return schema.PARTIAL, self._labelled(detail) |
| 246 | return None |
| 247 | |
| 248 | def _labelled(self, detail: str) -> str: |
| 249 | provenance = self.provenance |
| 250 | if provenance == PROVENANCE_NATIVE: |
| 251 | return detail.replace(_CONNECTOR_LABEL, _NATIVE_LABEL, 1) |
| 252 | if provenance == PROVENANCE_OPENCODE_BROWSE: |
| 253 | return detail.replace(_CONNECTOR_LABEL, _BROWSE_LABEL, 1) |
| 254 | return detail |
| 255 | |
| 256 | def receipt(self) -> str: |
| 257 | dropped = ", ".join( |
| 258 | f"{name} {count}" for name, count in self.counters.items() if count |
| 259 | ) or "none" |
| 260 | lanes = ", ".join(f"{lane} {self.lane_counts.get(lane, 0)}" for lane in LANES) |
| 261 | line = ( |
| 262 | f"host-fetched X: accepted {self.accepted} of {self.total} " |
| 263 | f"(dropped: {dropped}); lanes: {lanes}" |
| 264 | ) |
| 265 | if self.status != "ok": |
| 266 | line += f"; status {self.status}" |
| 267 | if self.error_category: |
| 268 | line += f" ({self.error_category})" |
| 269 | if self.notes: |
| 270 | line += "; notes: " + "; ".join(self.notes) |
| 271 | return line |
| 272 | |
| 273 | |
| 274 | def _error_outcome(category: str) -> tuple[schema.RunOutcomeState, str]: |
| 275 | if category == CATEGORY_CREDITS: |
| 276 | return schema.PAYMENT_REQUIRED, DETAIL_CREDITS |
| 277 | if category == CATEGORY_NOT_CONNECTED: |
| 278 | return health.ERROR, DETAIL_NOT_CONNECTED |
| 279 | if category == CATEGORY_UNAVAILABLE: |
| 280 | return health.ERROR, DETAIL_UNAVAILABLE |
| 281 | if category == _CATEGORY_GENERATED: |
| 282 | return health.ERROR, DETAIL_GENERATED |
| 283 | return health.ERROR, DETAIL_ERROR |
| 284 | |
| 285 | |
| 286 | # --------------------------------------------------------------------------- |
| 287 | # Helpers |
| 288 | # --------------------------------------------------------------------------- |
| 289 | |
| 290 | |
| 291 | def _stat(path: Path) -> os.stat_result: |
| 292 | """Seam for tests: the size and type check runs before any read.""" |
| 293 | return os.stat(path) |
| 294 | |
| 295 | |
| 296 | def _log(msg: str) -> None: |
| 297 | log.source_log("x", msg, tty_only=False) |
| 298 | |
| 299 | |
| 300 | def _protected_roots() -> list[Path]: |
| 301 | roots: list[Path] = [] |
| 302 | for candidate in (env.CONFIG_DIR, getattr(env, "CONFIG_FILE", None)): |
| 303 | if candidate: |
| 304 | roots.append(Path(candidate)) |
| 305 | for store in _CREDENTIAL_STORES: |
| 306 | roots.append(Path(store).expanduser()) |
| 307 | return [Path(os.path.realpath(root)) for root in roots] |
| 308 | |
| 309 | |
| 310 | def _inside_protected(real: Path) -> bool: |
| 311 | for root in _protected_roots(): |
| 312 | if real == root or root in real.parents: |
| 313 | return True |
| 314 | return False |
| 315 | |
| 316 | |
| 317 | def _normalize_topic(value: str) -> str: |
| 318 | cleaned = _CONTROL_ANY_RE.sub("", str(value or "")) |
| 319 | cleaned = cleaned.strip(_TOPIC_STRIP).casefold() |
| 320 | return " ".join(cleaned.split()) |
| 321 | |
| 322 | |
| 323 | def _parse_day(value: Any) -> date | None: |
| 324 | if not isinstance(value, str): |
| 325 | return None |
| 326 | try: |
| 327 | return date.fromisoformat(value.strip()[:10]) |
| 328 | except ValueError: |
| 329 | return None |
| 330 | |
| 331 | |
| 332 | def _parse_iso(value: str) -> datetime | None: |
| 333 | text = value.strip() |
| 334 | if text.endswith(("Z", "z")): |
| 335 | text = text[:-1] + "+00:00" |
| 336 | try: |
| 337 | parsed = datetime.fromisoformat(text) |
| 338 | except ValueError: |
| 339 | return None |
| 340 | if parsed.tzinfo is None: |
| 341 | parsed = parsed.replace(tzinfo=timezone.utc) |
| 342 | return parsed |
| 343 | |
| 344 | |
| 345 | def _category(raw: str) -> str: |
| 346 | """Allowlisted error class from the first token, or '' if unrecognized.""" |
| 347 | cleaned = _CONTROL_ANY_RE.sub("", raw or "").strip().lower() |
| 348 | if not cleaned: |
| 349 | return "" |
| 350 | token = cleaned.split()[0] |
| 351 | token = re.sub(r"[^a-z0-9-]", "", token) |
| 352 | return token if token in _ALLOWED_ERROR_CATEGORIES else "" |
| 353 | |
| 354 | |
| 355 | _MAX_UNESCAPE_PASSES = 3 |
| 356 | _ENTITY_PREFIX_RE = re.compile( |
| 357 | r"&(?=(?:#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]+);?)" |
| 358 | ) |
| 359 | # Valid Unicode code points are at most U+10FFFF (7 decimal / 6 hex digits). |
| 360 | # Longer numeric charrefs cannot decode to a valid code point and can raise |
| 361 | # ValueError under Python's int_max_str_digits limit inside html.unescape. |
| 362 | _OVERSIZED_NUMERIC_ENTITY_RE = re.compile( |
| 363 | r"&(?=#(?:[0-9]{8,}|[xX][0-9A-Fa-f]{7,});?)" |
| 364 | ) |
| 365 | |
| 366 | |
| 367 | def _safe_unescape(text: str) -> str: |
| 368 | """Decode HTML entities without raising on oversized numeric references.""" |
| 369 | safe = _OVERSIZED_NUMERIC_ENTITY_RE.sub("& ", text) |
| 370 | try: |
| 371 | return html.unescape(safe) |
| 372 | except ValueError: |
| 373 | return safe |
| 374 | |
| 375 | |
| 376 | def _clean_text(value: str) -> str: |
| 377 | """Unescape HTML entities, strip C0/C1 controls (newlines and tabs survive), |
| 378 | and defang markup. |
| 379 | |
| 380 | Envelope text is model-written and post-authored, so HTML entities are |
| 381 | decoded (bounded iterative unescape) before control-character stripping and |
| 382 | defanging. Any remaining entity layers past the pass cap are neutralized so |
| 383 | downstream ``html.unescape`` cannot re-introduce ``<!--``, ``](``, or |
| 384 | control bytes. The two Markdown constructs that stay active in the saved |
| 385 | report are neutralised without hiding the characters: a link tail ``](`` |
| 386 | becomes ``]\\(`` (renders as the same text, never as a link) and an HTML |
| 387 | comment opener ``<!--`` becomes ``<! --`` (never a comment, so a pasted |
| 388 | META marker cannot be promoted). Raw tags are left to the HTML renderer's |
| 389 | escaping. |
| 390 | """ |
| 391 | text = value |
| 392 | for _ in range(_MAX_UNESCAPE_PASSES): |
| 393 | text = text.replace("\r\n", "\n").replace("\r", "\n") |
| 394 | text = _CONTROL_TEXT_RE.sub("", text) |
| 395 | if "&" not in text: |
| 396 | break |
| 397 | unescaped = _safe_unescape(text) |
| 398 | if unescaped == text: |
| 399 | break |
| 400 | text = unescaped |
| 401 | else: |
| 402 | text = text.replace("\r\n", "\n").replace("\r", "\n") |
| 403 | text = _CONTROL_TEXT_RE.sub("", text) |
| 404 | if "&" in text and _safe_unescape(text) != text: |
| 405 | text = _ENTITY_PREFIX_RE.sub("& ", text) |
| 406 | text = text.replace("\r\n", "\n").replace("\r", "\n") |
| 407 | text = _CONTROL_TEXT_RE.sub("", text) |
| 408 | return text.replace("](", "]\\(").replace("<!--", "<! --") |
| 409 | |
| 410 | |
| 411 | def _int(value: Any) -> int | None: |
| 412 | if value is None or isinstance(value, bool): |
| 413 | return None |
| 414 | if isinstance(value, float) and not math.isfinite(value): |
| 415 | return None |
| 416 | try: |
| 417 | parsed = int(value) |
| 418 | except (TypeError, ValueError, OverflowError): |
| 419 | return None |
| 420 | if parsed < 0 or parsed > MAX_ENGAGEMENT_COUNT: |
| 421 | return None |
| 422 | return parsed |
| 423 | |
| 424 | |
| 425 | def _reject_constant(token: str) -> Any: |
| 426 | raise ValueError(f"invalid JSON constant: {token}") |
| 427 | |
| 428 | |
| 429 | def _post_id(value: Any) -> str: |
| 430 | if isinstance(value, bool): |
| 431 | return "" |
| 432 | if isinstance(value, int): |
| 433 | candidate = str(value) |
| 434 | elif isinstance(value, str): |
| 435 | candidate = value.strip() |
| 436 | else: |
| 437 | return "" |
| 438 | if not candidate.isdigit() or len(candidate) > MAX_ID_DIGITS: |
| 439 | return "" |
| 440 | return candidate |
| 441 | |
| 442 | |
| 443 | def _handle(value: Any) -> str: |
| 444 | if not isinstance(value, str) or _CONTROL_ANY_RE.search(value): |
| 445 | return "" |
| 446 | handle = _clean_handle(value) |
| 447 | if handle.lower() in _PLACEHOLDER_HANDLES: |
| 448 | return "" |
| 449 | return handle |
| 450 | |
| 451 | |
| 452 | def _clean_handles(value: Any) -> list[str] | None: |
| 453 | """Grammar-valid, lowercased handles; ``None`` when any entry fails.""" |
| 454 | if not isinstance(value, list): |
| 455 | return None |
| 456 | cleaned: list[str] = [] |
| 457 | for raw in value: |
| 458 | handle = _handle(raw) |
| 459 | if not handle: |
| 460 | return None |
| 461 | if handle.lower() not in cleaned: |
| 462 | cleaned.append(handle.lower()) |
| 463 | return cleaned |
| 464 | |
| 465 | |
| 466 | # --------------------------------------------------------------------------- |
| 467 | # Reader |
| 468 | # --------------------------------------------------------------------------- |
| 469 | |
| 470 | |
| 471 | # Clock skew a host may legitimately show; anything further ahead is a |
| 472 | # stamp chosen to outlive the six-hour freshness gate. |
| 473 | FUTURE_SKEW_SECONDS = 5 * 60 |
| 474 | |
| 475 | |
| 476 | def _generated_in_future(value: Any) -> bool: |
| 477 | """True when ``generated_at`` is more than ``FUTURE_SKEW_SECONDS`` ahead of now.""" |
| 478 | try: |
| 479 | stamp = datetime.fromisoformat(str(value)) |
| 480 | except (TypeError, ValueError): |
| 481 | return False |
| 482 | if stamp.tzinfo is None: |
| 483 | stamp = stamp.replace(tzinfo=timezone.utc) |
| 484 | ahead = stamp.astimezone(timezone.utc) - datetime.now(timezone.utc) |
| 485 | return ahead.total_seconds() > FUTURE_SKEW_SECONDS |
| 486 | |
| 487 | |
| 488 | def read( |
| 489 | path: str | os.PathLike[str], |
| 490 | window: tuple[str, str], |
| 491 | topic: str, |
| 492 | handles: list[str] | None = None, |
| 493 | related: list[str] | None = None, |
| 494 | ) -> Envelope: |
| 495 | """Validate and ingest a ``--x-posts`` file for this run. |
| 496 | |
| 497 | ``window`` is the engine's ``(from_date, to_date)``; ``topic`` is the run |
| 498 | topic (or comparison entity); ``handles`` are the run's ``--x-handle`` |
| 499 | handles and ``related`` its ``--x-related`` handles, which together bound |
| 500 | what a call's ``handles`` may claim. |
| 501 | |
| 502 | Raises ``EnvelopeContractError`` (exit 2) for every fail-closed case. |
| 503 | """ |
| 504 | raw_path = os.fspath(path) |
| 505 | |
| 506 | def fail(what: str) -> EnvelopeContractError: |
| 507 | return EnvelopeContractError(f"--x-posts file {raw_path} {what}. {_REMEDY}") |
| 508 | |
| 509 | real = Path(os.path.realpath(raw_path)) |
| 510 | try: |
| 511 | info = _stat(real) |
| 512 | except OSError as exc: |
| 513 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 514 | if not stat.S_ISREG(info.st_mode): |
| 515 | raise fail("is not a regular file") |
| 516 | if real.suffix.lower() != ".json": |
| 517 | raise fail("must be a .json file") |
| 518 | if _inside_protected(real): |
| 519 | raise fail("is inside a configuration or credential directory") |
| 520 | if info.st_size > MAX_BYTES: |
| 521 | raise fail(f"exceeds the {MAX_BYTES // (1024 * 1024)} MiB limit") |
| 522 | |
| 523 | try: |
| 524 | data = real.read_bytes() |
| 525 | except OSError as exc: |
| 526 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 527 | digest = hashlib.sha256(data).hexdigest() |
| 528 | try: |
| 529 | text = data.decode("utf-8") |
| 530 | except UnicodeDecodeError: |
| 531 | raise fail("is not valid UTF-8") from None |
| 532 | try: |
| 533 | payload = json.loads(text, parse_constant=_reject_constant) |
| 534 | except (RecursionError, MemoryError): |
| 535 | raise fail("is too deeply nested or too large to parse") from None |
| 536 | except ValueError: |
| 537 | raise fail("is not valid JSON") from None |
| 538 | |
| 539 | if not isinstance(payload, dict): |
| 540 | raise fail("must be a JSON object") |
| 541 | if payload.get("schema") != SCHEMA: |
| 542 | raise fail('has a missing or unsupported "schema" field') |
| 543 | status = payload.get("status") |
| 544 | if status not in STATUSES: |
| 545 | raise fail('has a "status" field that is not ok, partial, or error') |
| 546 | if not env.is_timestamp_fresh(payload.get("generated_at"), MAX_AGE_SECONDS): |
| 547 | raise fail( |
| 548 | 'has a "generated_at" field that is missing, malformed, or older than ' |
| 549 | f"{MAX_AGE_SECONDS // 3600} hours" |
| 550 | ) |
| 551 | if _generated_in_future(payload.get("generated_at")): |
| 552 | raise fail('has a "generated_at" field in the future') |
| 553 | if _normalize_topic(payload.get("topic")) != _normalize_topic(topic) or not _normalize_topic(topic): |
| 554 | raise fail('has a "topic" field that does not match this run\'s topic') |
| 555 | |
| 556 | from_date, to_date = window |
| 557 | window_raw = payload.get("window") |
| 558 | if not isinstance(window_raw, dict): |
| 559 | raise fail('has a missing or malformed "window" field') |
| 560 | window_from = _parse_day(window_raw.get("from")) |
| 561 | window_to = _parse_day(window_raw.get("to")) |
| 562 | if window_from is None or window_to is None: |
| 563 | raise fail('has a "window" field without valid from/to dates') |
| 564 | engine_from = _parse_day(from_date) or date.min |
| 565 | engine_to = _parse_day(to_date) or date.max |
| 566 | if window_to < engine_from: |
| 567 | raise fail('has a "window" that ends before the research window starts') |
| 568 | warnings: list[str] = [] |
| 569 | if window_from > engine_from or window_to < engine_to: |
| 570 | warnings.append( |
| 571 | f"host-fetched X window {window_from.isoformat()}..{window_to.isoformat()} " |
| 572 | f"is narrower than the research window {from_date}..{to_date}; " |
| 573 | "the research window is authoritative" |
| 574 | ) |
| 575 | |
| 576 | provider = _CONTROL_ANY_RE.sub("", str(payload.get("provider") or ""))[:64].strip() |
| 577 | |
| 578 | error_raw = payload.get("error") |
| 579 | if error_raw is not None and not isinstance(error_raw, str): |
| 580 | raise fail('has an "error" field that is not a string') |
| 581 | if error_raw and ("\n" in error_raw or "\r" in error_raw): |
| 582 | raise fail('has an "error" field that is not a single line') |
| 583 | error_category = _category(error_raw or "") |
| 584 | if error_raw and log.is_debug(): |
| 585 | _log(f"envelope error text (debug only): {_CONTROL_ANY_RE.sub('', error_raw)[:500]}") |
| 586 | |
| 587 | calls_raw = payload.get("calls") |
| 588 | if not isinstance(calls_raw, list): |
| 589 | raise fail('has a "calls" field that is not a list') |
| 590 | if len(calls_raw) > MAX_CALLS: |
| 591 | raise fail(f'has more than {MAX_CALLS} entries in "calls"') |
| 592 | if not calls_raw and status == "ok": |
| 593 | raise fail('has an empty "calls" list with status ok') |
| 594 | |
| 595 | allowed = {h.lower() for h in (_clean_handles(list(handles or [])) or [])} |
| 596 | related_set = {h.lower() for h in (_clean_handles(list(related or [])) or [])} |
| 597 | allowed |= related_set |
| 598 | |
| 599 | counters: dict[str, int] = {name: 0 for name in COUNTERS} |
| 600 | lane_counts: dict[str, int] = {lane: 0 for lane in LANES} |
| 601 | notes: list[str] = [] |
| 602 | call_lanes: list[str] = [] |
| 603 | topic_items: list[dict[str, Any]] = [] |
| 604 | lane_calls: list[EnvelopeCall] = [] |
| 605 | seen_ids: set[str] = set() |
| 606 | kept_ids: list[str] = [] |
| 607 | total = 0 |
| 608 | now_plus = datetime.now(timezone.utc) + timedelta(days=1) |
| 609 | |
| 610 | for index, call in enumerate(calls_raw, start=1): |
| 611 | if not isinstance(call, dict): |
| 612 | raise fail(f"has a call {index} that is not an object") |
| 613 | posts = call.get("posts") |
| 614 | if not isinstance(posts, list) or any(not isinstance(row, dict) for row in posts): |
| 615 | raise fail(f'has a call {index} whose "posts" is not a list of objects') |
| 616 | if len(posts) > MAX_ROWS_PER_CALL: |
| 617 | raise fail(f"has a call {index} with more than {MAX_ROWS_PER_CALL} rows") |
| 618 | total += len(posts) |
| 619 | if total > MAX_ROWS_TOTAL: |
| 620 | raise fail(f"has more than {MAX_ROWS_TOTAL} rows in total") |
| 621 | |
| 622 | lane_raw = call.get("lane") |
| 623 | lane = lane_raw.strip().lower() if isinstance(lane_raw, str) else "" |
| 624 | call_handles = _clean_handles(call.get("handles")) |
| 625 | if lane not in LANES: |
| 626 | if lane_raw is not None: |
| 627 | counters["lane-mismatch"] += 1 |
| 628 | notes.append(f"call {index}: unknown lane served as topic") |
| 629 | lane = "topic" |
| 630 | call_handles = [] |
| 631 | elif lane != "topic": |
| 632 | valid = bool(call_handles) and set(call_handles) <= allowed |
| 633 | if valid and lane == "related": |
| 634 | valid = set(call_handles) <= related_set |
| 635 | if not valid: |
| 636 | counters["lane-mismatch"] += 1 |
| 637 | notes.append( |
| 638 | f"call {index}: {lane} lane served as topic " |
| 639 | "(handles are not in --x-handle/--x-related)" |
| 640 | ) |
| 641 | lane = "topic" |
| 642 | call_handles = [] |
| 643 | else: |
| 644 | call_handles = [] |
| 645 | call_lanes.append(lane) |
| 646 | |
| 647 | kept: list[dict[str, Any]] = [] |
| 648 | for row in posts: |
| 649 | item = _ingest_row( |
| 650 | row, topic=topic, from_date=from_date, to_date=to_date, |
| 651 | now_plus=now_plus, seen_ids=seen_ids, counters=counters, |
| 652 | ) |
| 653 | if item is None: |
| 654 | continue |
| 655 | author = item["author_handle"].lower() |
| 656 | if lane == "from" or lane == "related": |
| 657 | if author not in call_handles: |
| 658 | counters["lane-mismatch"] += 1 |
| 659 | seen_ids.discard(item["post_id"]) |
| 660 | continue |
| 661 | elif lane == "mention": |
| 662 | if author in call_handles or any( |
| 663 | is_own_post(item["url"], handle) for handle in call_handles |
| 664 | ): |
| 665 | counters["lane-mismatch"] += 1 |
| 666 | seen_ids.discard(item["post_id"]) |
| 667 | continue |
| 668 | kept.append(item) |
| 669 | kept_ids.append(item["post_id"]) |
| 670 | |
| 671 | lane_counts[lane] += len(kept) |
| 672 | if lane == "topic": |
| 673 | topic_items.extend(kept) |
| 674 | else: |
| 675 | lane_calls.append(EnvelopeCall(index=index, lane=lane, handles=call_handles, posts=kept)) |
| 676 | |
| 677 | accepted = len(kept_ids) |
| 678 | if status == "error": |
| 679 | # An error envelope carries no evidence: the outcome is the story. |
| 680 | topic_items, lane_calls = [], [] |
| 681 | lane_counts = {lane: 0 for lane in LANES} |
| 682 | accepted = 0 |
| 683 | elif kept_ids and _looks_generated(kept_ids): |
| 684 | status = "error" |
| 685 | error_category = _CATEGORY_GENERATED |
| 686 | topic_items, lane_calls = [], [] |
| 687 | lane_counts = {lane: 0 for lane in LANES} |
| 688 | accepted = 0 |
| 689 | notes.append("id sequence looks generated; envelope rejected") |
| 690 | |
| 691 | for position, item in enumerate( |
| 692 | [*topic_items, *(post for call in lane_calls for post in call.posts)], start=1 |
| 693 | ): |
| 694 | item["id"] = f"{ID_PREFIX}{position}" |
| 695 | |
| 696 | envelope = Envelope( |
| 697 | path=raw_path, |
| 698 | sha256=digest, |
| 699 | status=status, |
| 700 | error_category=error_category, |
| 701 | provider=provider, |
| 702 | window=(window_from.isoformat(), window_to.isoformat()), |
| 703 | topic_items=topic_items, |
| 704 | lane_calls=lane_calls, |
| 705 | counters=counters, |
| 706 | accepted=accepted, |
| 707 | total=total, |
| 708 | lane_counts=lane_counts, |
| 709 | call_lanes=call_lanes, |
| 710 | warnings=warnings, |
| 711 | notes=notes, |
| 712 | ) |
| 713 | _log(envelope.receipt()) |
| 714 | for warning in warnings: |
| 715 | _log(warning) |
| 716 | return envelope |
| 717 | |
| 718 | |
| 719 | def _ingest_row( |
| 720 | row: dict[str, Any], |
| 721 | *, |
| 722 | topic: str, |
| 723 | from_date: str, |
| 724 | to_date: str, |
| 725 | now_plus: datetime, |
| 726 | seen_ids: set[str], |
| 727 | counters: dict[str, int], |
| 728 | ) -> dict[str, Any] | None: |
| 729 | """Rebuild one flat row into the engine's X item shape, or drop it. |
| 730 | |
| 731 | Returns ``None`` after incrementing the matching counter. The citation |
| 732 | URL is always engine-built from the id and the validated handle. |
| 733 | """ |
| 734 | if set(row) - ROW_FIELDS: |
| 735 | counters["extra-fields"] += 1 |
| 736 | |
| 737 | post_id = _post_id(row.get("id")) |
| 738 | text_raw = row.get("text") |
| 739 | text = _clean_text(text_raw) if isinstance(text_raw, str) else "" |
| 740 | if not post_id or not text.strip(): |
| 741 | counters["missing-id-text"] += 1 |
| 742 | return None |
| 743 | text = text.strip() |
| 744 | if len(text) > MAX_TEXT_CHARS: |
| 745 | text = text[:MAX_TEXT_CHARS] |
| 746 | counters["truncated"] += 1 |
| 747 | |
| 748 | decoded = _decode_snowflake(post_id) |
| 749 | if decoded is None or decoded < _SNOWFLAKE_FLOOR or decoded > now_plus: |
| 750 | counters["out-of-window"] += 1 |
| 751 | return None |
| 752 | snowflake_day = decoded.date() |
| 753 | |
| 754 | created_raw = row.get("created_at") |
| 755 | if isinstance(created_raw, str) and created_raw.strip(): |
| 756 | created = _parse_iso(created_raw) |
| 757 | if created is not None and abs((created.date() - snowflake_day).days) > 1: |
| 758 | counters["date-mismatch"] += 1 |
| 759 | return None |
| 760 | |
| 761 | day = snowflake_day.isoformat() |
| 762 | if (from_date and day < from_date) or (to_date and day > to_date): |
| 763 | counters["out-of-window"] += 1 |
| 764 | return None |
| 765 | |
| 766 | if post_id in seen_ids: |
| 767 | counters["duplicate"] += 1 |
| 768 | return None |
| 769 | seen_ids.add(post_id) |
| 770 | |
| 771 | handle = _handle(row.get("author_handle")) |
| 772 | url_raw = row.get("url") |
| 773 | if isinstance(url_raw, str) and url_raw.strip(): |
| 774 | match = _STATUS_URL_RE.match(url_raw.strip()) |
| 775 | url_handle = match.group("handle").lower() if match else "" |
| 776 | consistent = bool(match) and match.group("id") == post_id and ( |
| 777 | url_handle == "i" or not handle or url_handle == handle.lower() |
| 778 | ) |
| 779 | if not consistent: |
| 780 | counters["handle-mismatch"] += 1 |
| 781 | handle = "" |
| 782 | |
| 783 | if handle: |
| 784 | url = f"https://x.com/{handle}/status/{post_id}" |
| 785 | else: |
| 786 | counters["uncitable"] += 1 |
| 787 | url = f"https://x.com/i/status/{post_id}" |
| 788 | |
| 789 | return { |
| 790 | "id": "", |
| 791 | "text": text, |
| 792 | "url": url, |
| 793 | "author_handle": handle, |
| 794 | "date": day, |
| 795 | "engagement": { |
| 796 | "likes": _int(row.get("likes")), |
| 797 | "reposts": _int(row.get("reposts")), |
| 798 | "replies": _int(row.get("replies")), |
| 799 | "quotes": _int(row.get("quotes")), |
| 800 | }, |
| 801 | "mentioned_handles": leading_mentions(text), |
| 802 | "why_relevant": "", |
| 803 | "relevance": _compute_relevance(topic, text) if topic else 0.5, |
| 804 | "post_id": post_id, |
| 805 | } |
| 806 |