| 1 | #!/usr/bin/env python3 |
| 2 | # fmt: off |
| 3 | # ruff: noqa: E402 |
| 4 | """last30days CLI.""" |
| 5 | |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | import argparse |
| 9 | import atexit |
| 10 | import datetime |
| 11 | import hashlib |
| 12 | import json |
| 13 | import os |
| 14 | import re |
| 15 | import signal |
| 16 | import sqlite3 |
| 17 | import sys |
| 18 | import time |
| 19 | import uuid |
| 20 | from collections.abc import Callable, Iterator |
| 21 | from contextlib import contextmanager |
| 22 | from pathlib import Path |
| 23 | from typing import NamedTuple |
| 24 | |
| 25 | MIN_PYTHON = (3, 12) |
| 26 | |
| 27 | |
| 28 | def ensure_supported_python(version_info: tuple[int, int, int] | object | None = None) -> None: |
| 29 | if version_info is None: |
| 30 | version_info = sys.version_info |
| 31 | major, minor, micro = tuple(version_info[:3]) |
| 32 | if (major, minor) >= MIN_PYTHON: |
| 33 | return |
| 34 | req = f"{MIN_PYTHON[0]}.{MIN_PYTHON[1]}" |
| 35 | sys.stderr.write( |
| 36 | f"last30days v4 requires Python {req}+.\n" |
| 37 | f"Detected Python {major}.{minor}.{micro}.\n" |
| 38 | f"Install with:\n" |
| 39 | f" Mac: brew install python@{req}\n" |
| 40 | f" Windows: winget install Python.Python.{req}\n" |
| 41 | f" Linux: sudo apt install python{req} (or pyenv install {req})\n" |
| 42 | f"Then rerun: python{req} <path-to-script> setup\n" |
| 43 | ) |
| 44 | raise SystemExit(1) |
| 45 | |
| 46 | |
| 47 | ensure_supported_python() |
| 48 | |
| 49 | # Installed skill directories hold source; runtime imports must not add caches. |
| 50 | sys.dont_write_bytecode = True |
| 51 | |
| 52 | if os.name == "nt": |
| 53 | for stream in (sys.stdout, sys.stderr): |
| 54 | if hasattr(stream, "reconfigure"): |
| 55 | stream.reconfigure(encoding="utf-8", errors="replace") |
| 56 | |
| 57 | SCRIPT_DIR = Path(__file__).parent.resolve() |
| 58 | sys.path.insert(0, str(SCRIPT_DIR)) |
| 59 | |
| 60 | from lib import company_resolve, competitors as competitors_mod, corpus, dates, discovery_handoff, env, fetch_memo, freshness, health, html_render, http, patents, permission_preflight, person, pipeline, proxy, reddit, reddit_arctic, reddit_discover, reddit_envelope, reddit_health, reddit_search, reddit_session, registers, render, report_checklist, schema, shortform_envelope, subproc, ui, web_search_keyless, x_envelope, yahoo_finance |
| 61 | from lib.private_files import replace_private_text |
| 62 | |
| 63 | atexit.register(subproc.cleanup_children) |
| 64 | |
| 65 | |
| 66 | def _on_sigterm(signum, frame) -> None: |
| 67 | """SIGTERM handler: clean descendant groups, then die as SIGTERM. |
| 68 | |
| 69 | Every run_with_timeout child runs in its own pgid (lib/subproc.py via |
| 70 | os.setsid), so a group kill aimed at the engine can never reach them; |
| 71 | only the lib.subproc registry can. atexit never runs on a signal death, |
| 72 | so without this handler an MCP timeout would orphan node bird-search, |
| 73 | yt-dlp, and the digg CLI. The MCP server SIGTERMs the engine group |
| 74 | first, giving this handler room to killpg() each registered child |
| 75 | group before the SIGKILL backstop. Restoring the default disposition |
| 76 | and re-raising preserves killed-by-SIGTERM semantics for the parent. |
| 77 | """ |
| 78 | subproc.cleanup_children() |
| 79 | signal.signal(signal.SIGTERM, signal.SIG_DFL) |
| 80 | os.kill(os.getpid(), signal.SIGTERM) |
| 81 | |
| 82 | |
| 83 | def _install_sigterm_handler() -> None: |
| 84 | try: |
| 85 | signal.signal(signal.SIGTERM, _on_sigterm) |
| 86 | except (ValueError, OSError, RuntimeError): |
| 87 | pass |
| 88 | |
| 89 | |
| 90 | def parse_meta_ads_page(raw: str) -> str: |
| 91 | """Extract an Ad Library page id from a flag value, or "" if there is none. |
| 92 | |
| 93 | Accepts a bare numeric id or any Ad Library URL carrying |
| 94 | ``view_all_page_id``. A ``facebook.com/<vanity>`` URL is deliberately |
| 95 | rejected rather than guessed at: a vanity handle is not a page id, and one |
| 96 | live check resolved a brand-looking handle to a private person's profile. |
| 97 | """ |
| 98 | value = str(raw or "").strip() |
| 99 | if not value: |
| 100 | return "" |
| 101 | if re.fullmatch(r"\d{5,20}", value): |
| 102 | return value |
| 103 | match = re.search(r"view_all_page_id=(\d{5,20})", value) |
| 104 | return match.group(1) if match else "" |
| 105 | |
| 106 | |
| 107 | def parse_search_flag(raw: str, flag_name: str = "--search") -> list[str]: |
| 108 | sources = [] |
| 109 | for source in raw.split(","): |
| 110 | source = source.strip().lower() |
| 111 | if not source: |
| 112 | continue |
| 113 | normalized = pipeline.SEARCH_ALIAS.get(source, source) |
| 114 | if normalized not in pipeline.KNOWN_SEARCH_SOURCES: |
| 115 | raise SystemExit(f"Unknown search source in {flag_name}: {source}") |
| 116 | if normalized not in sources: |
| 117 | sources.append(normalized) |
| 118 | if not sources: |
| 119 | raise SystemExit(f"{flag_name} requires at least one source.") |
| 120 | return sources |
| 121 | |
| 122 | def parse_as_of_date_arg(value: str) -> str: |
| 123 | try: |
| 124 | parsed = dates.parse_as_of_date(value) |
| 125 | except ValueError as exc: |
| 126 | raise argparse.ArgumentTypeError(str(exc)) from exc |
| 127 | return parsed |
| 128 | |
| 129 | def resolve_requested_sources(args_search: str | None, config: dict) -> list[str] | None: |
| 130 | """Resolve the requested source set: explicit --search wins, then the |
| 131 | LAST30DAYS_DEFAULT_SEARCH config key (env var or .env file), then None |
| 132 | (per-query default behavior). The config fallback lets users pin a fixed |
| 133 | source set that survives upgrades without patching SKILL.md (#442). |
| 134 | """ |
| 135 | if args_search: |
| 136 | return parse_search_flag(args_search) |
| 137 | default_search = (config.get("LAST30DAYS_DEFAULT_SEARCH") or "").strip() |
| 138 | if default_search: |
| 139 | return parse_search_flag(default_search, flag_name="LAST30DAYS_DEFAULT_SEARCH") |
| 140 | return None |
| 141 | |
| 142 | |
| 143 | def add_deep_research_source( |
| 144 | requested_sources: list[str] | None, |
| 145 | ) -> list[str] | None: |
| 146 | """Add Perplexity without replacing the default-source sentinel. |
| 147 | |
| 148 | ``None`` means that the planner can use the normal configured source set. |
| 149 | Deep Research enables Perplexity through ``INCLUDE_SOURCES`` separately, so |
| 150 | converting this sentinel to ``["perplexity"]`` would suppress every normal |
| 151 | source. |
| 152 | """ |
| 153 | if requested_sources is None: |
| 154 | return None |
| 155 | if "perplexity" in requested_sources: |
| 156 | return requested_sources |
| 157 | return [*requested_sources, "perplexity"] |
| 158 | |
| 159 | |
| 160 | def enable_deep_research_source(config: dict) -> None: |
| 161 | """Enable the exact Perplexity token or reject a hard exclusion.""" |
| 162 | excluded = { |
| 163 | token.strip().lower() |
| 164 | for token in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 165 | if token.strip() |
| 166 | } |
| 167 | if "perplexity" in excluded: |
| 168 | raise ValueError( |
| 169 | "--deep-research conflicts with EXCLUDE_SOURCES=perplexity" |
| 170 | ) |
| 171 | |
| 172 | include = str(config.get("INCLUDE_SOURCES") or "") |
| 173 | tokens = [token.strip() for token in include.split(",") if token.strip()] |
| 174 | if "perplexity" not in {token.lower() for token in tokens}: |
| 175 | tokens.append("perplexity") |
| 176 | config["INCLUDE_SOURCES"] = ",".join(tokens) |
| 177 | |
| 178 | |
| 179 | def plan_has_explicit_trustpilot_domain(comp_plan: dict | None) -> bool: |
| 180 | """True when any --competitors-plan entry pins a trustpilot_domain.""" |
| 181 | if not comp_plan: |
| 182 | return False |
| 183 | for entry in comp_plan.values(): |
| 184 | if not isinstance(entry, dict): |
| 185 | continue |
| 186 | domain = entry.get("trustpilot_domain") |
| 187 | if isinstance(domain, str) and domain.strip(): |
| 188 | return True |
| 189 | return False |
| 190 | |
| 191 | |
| 192 | def activate_trustpilot_for_explicit_domain( |
| 193 | config: dict, |
| 194 | requested_sources: list[str] | None, |
| 195 | *, |
| 196 | reason: str, |
| 197 | ) -> list[str] | None: |
| 198 | """Activate the opt-in Trustpilot source when the user pinned a domain. |
| 199 | |
| 200 | Passing ``--trustpilot-domain`` (or a plan-level ``trustpilot_domain``) is |
| 201 | unambiguous intent — silently ignoring it when Trustpilot is not in |
| 202 | ``INCLUDE_SOURCES`` / ``--search`` is the #873 failure mode. Auto-resolve |
| 203 | hints must not call this helper. |
| 204 | |
| 205 | ``EXCLUDE_SOURCES=trustpilot`` still wins. Mutates ``config`` in place and |
| 206 | returns the (possibly extended) ``requested_sources`` list. |
| 207 | """ |
| 208 | excluded = { |
| 209 | token.strip().lower() |
| 210 | for token in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 211 | if token.strip() |
| 212 | } |
| 213 | if "trustpilot" in excluded: |
| 214 | sys.stderr.write( |
| 215 | f"[Trustpilot] {reason} ignored: trustpilot is in EXCLUDE_SOURCES\n" |
| 216 | ) |
| 217 | return requested_sources |
| 218 | |
| 219 | include = str(config.get("INCLUDE_SOURCES") or "") |
| 220 | tokens = [token.strip() for token in include.split(",") if token.strip()] |
| 221 | if "trustpilot" not in {token.lower() for token in tokens}: |
| 222 | tokens.append("trustpilot") |
| 223 | config["INCLUDE_SOURCES"] = ",".join(tokens) |
| 224 | sys.stderr.write( |
| 225 | f"[Trustpilot] {reason} activated trustpilot source " |
| 226 | "(add to INCLUDE_SOURCES permanently to skip this auto-enable)\n" |
| 227 | ) |
| 228 | |
| 229 | if requested_sources is not None and "trustpilot" not in requested_sources: |
| 230 | requested_sources = [*requested_sources, "trustpilot"] |
| 231 | return requested_sources |
| 232 | |
| 233 | |
| 234 | def activate_telegram_for_explicit_sources( |
| 235 | config: dict, |
| 236 | requested_sources: list[str] | None, |
| 237 | *, |
| 238 | channels: str, |
| 239 | ) -> list[str] | None: |
| 240 | """Activate the opt-in Telegram source when the user pinned channel(s). |
| 241 | |
| 242 | Passing ``--telegram-sources`` is unambiguous intent — silently ignoring it |
| 243 | when Telegram is not in ``INCLUDE_SOURCES`` / ``--search`` is the same |
| 244 | failure mode as #873 (Trustpilot). Auto-activate the source. |
| 245 | |
| 246 | ``EXCLUDE_SOURCES=telegram`` still wins. Mutates ``config`` in place and |
| 247 | returns the (possibly extended) ``requested_sources`` list. |
| 248 | """ |
| 249 | excluded = { |
| 250 | token.strip().lower() |
| 251 | for token in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 252 | if token.strip() |
| 253 | } |
| 254 | if "telegram" in excluded: |
| 255 | sys.stderr.write( |
| 256 | f"[Telegram] --telegram-sources={channels} ignored: telegram is in EXCLUDE_SOURCES\n" |
| 257 | ) |
| 258 | return requested_sources |
| 259 | |
| 260 | config["TELEGRAM_SOURCES"] = channels |
| 261 | |
| 262 | include = str(config.get("INCLUDE_SOURCES") or "") |
| 263 | tokens = [token.strip() for token in include.split(",") if token.strip()] |
| 264 | if "telegram" not in {token.lower() for token in tokens}: |
| 265 | tokens.append("telegram") |
| 266 | config["INCLUDE_SOURCES"] = ",".join(tokens) |
| 267 | sys.stderr.write( |
| 268 | f"[Telegram] --telegram-sources={channels} activated telegram source " |
| 269 | "(add to INCLUDE_SOURCES permanently to skip this auto-enable)\n" |
| 270 | ) |
| 271 | |
| 272 | if requested_sources is not None and "telegram" not in requested_sources: |
| 273 | requested_sources = [*requested_sources, "telegram"] |
| 274 | return requested_sources |
| 275 | |
| 276 | |
| 277 | def slugify(value: str, max_length: int = 180) -> str: |
| 278 | from lib import library |
| 279 | |
| 280 | return library.filename_slug(library.slugify(value), max_length) |
| 281 | |
| 282 | |
| 283 | def sanitize_suffix(suffix: str) -> str: |
| 284 | """Sanitize a user-provided ``--save-suffix`` into a path-safe token. |
| 285 | |
| 286 | The suffix is glued directly into the saved-report filename, so restrict it |
| 287 | to the same ``[a-z0-9-]`` class as the topic slug. This neutralizes path |
| 288 | separators and parent refs (``/``, ``..``) so a suffix can never escape the |
| 289 | save directory, while leaving ordinary values ('v3', 'gemini', a client |
| 290 | slug) unchanged. Unlike ``slugify`` there is no fallback token: a suffix |
| 291 | that sanitizes to nothing simply drops, yielding no suffix part. |
| 292 | """ |
| 293 | return re.sub(r"[^a-z0-9]+", "-", suffix.lower()).strip("-") |
| 294 | |
| 295 | |
| 296 | def _report_has_private_corpus(report: schema.Report) -> bool: |
| 297 | items_by_source = getattr(report, "items_by_source", {}) |
| 298 | if isinstance(items_by_source, dict) and items_by_source.get("corpus"): |
| 299 | return True |
| 300 | if isinstance(report, schema.Report) and schema.partition_freshness_verdicts(report, {"corpus"})[1]: |
| 301 | return True |
| 302 | candidates = getattr(report, "ranked_candidates", ()) |
| 303 | if not isinstance(candidates, (list, tuple)): |
| 304 | return False |
| 305 | return any(schema.candidate_has_corpus(candidate) for candidate in candidates) |
| 306 | |
| 307 | |
| 308 | def _ensure_output_directory(path: Path, *, private: bool) -> None: |
| 309 | if not private: |
| 310 | path.mkdir(parents=True, exist_ok=True) |
| 311 | return |
| 312 | missing: list[Path] = [] |
| 313 | current = path |
| 314 | while not current.exists(): |
| 315 | missing.append(current) |
| 316 | current = current.parent |
| 317 | path.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 318 | for directory in missing: |
| 319 | directory.chmod(0o700) |
| 320 | |
| 321 | |
| 322 | def save_output( |
| 323 | report: schema.Report, |
| 324 | emit: str, |
| 325 | save_dir: str, |
| 326 | suffix: str = "", |
| 327 | synthesis_md: str | None = None, |
| 328 | topic_override: str | None = None, |
| 329 | rendered_content: str | None = None, |
| 330 | json_profile: str = "agent", |
| 331 | register: str = "default", |
| 332 | private: bool | None = None, |
| 333 | render_fn: Callable[[Path], str] | None = None, |
| 334 | ) -> Path: |
| 335 | from datetime import datetime |
| 336 | if save_dir is None or str(save_dir) == "" or pipeline.is_blank_save_dir(save_dir): |
| 337 | raise ValueError("save_output requires a non-empty save_dir") |
| 338 | path = Path(save_dir).expanduser().resolve() |
| 339 | slug = slugify(topic_override or report.topic) |
| 340 | extension = "json" if emit == "json" else "html" if emit == "html" else "md" |
| 341 | raw_label = "raw-html" if emit == "html" else "raw" |
| 342 | safe_suffix = sanitize_suffix(suffix) |
| 343 | suffix_part = f"-{safe_suffix}" if safe_suffix else "" |
| 344 | base = path / f"{slug}-{raw_label}{suffix_part}.{extension}" |
| 345 | date_str = datetime.now().strftime('%Y-%m-%d') |
| 346 | candidates = [base] |
| 347 | candidates.append(path / f"{slug}-{raw_label}{suffix_part}-{date_str}.{extension}") |
| 348 | for i in range(1, 100): |
| 349 | candidates.append(path / f"{slug}-{raw_label}{suffix_part}-{date_str}-{i}.{extension}") |
| 350 | # Markdown saves keep the complete debug artifact. JSON and HTML preserve |
| 351 | # their requested wire format so file extensions match their content. |
| 352 | # When render_fn is supplied, content is produced after O_EXCL allocates |
| 353 | # the candidate. This lets the footer cite the file actually written |
| 354 | # without racing a separate filesystem probe. |
| 355 | if render_fn is None: |
| 356 | if rendered_content is not None: |
| 357 | static_content = rendered_content |
| 358 | elif emit in {"json", "html"}: |
| 359 | static_content = emit_output( |
| 360 | report, |
| 361 | emit, |
| 362 | synthesis_md=synthesis_md, |
| 363 | json_profile=json_profile, |
| 364 | register=register, |
| 365 | ) |
| 366 | else: |
| 367 | static_content = render.render_full(report) |
| 368 | private_corpus = _report_has_private_corpus(report) or bool(private) |
| 369 | _ensure_output_directory(path, private=private_corpus) |
| 370 | for candidate in candidates: |
| 371 | try: |
| 372 | fd = os.open( |
| 373 | candidate, |
| 374 | os.O_CREAT | os.O_EXCL | os.O_WRONLY, |
| 375 | 0o600 if private_corpus else 0o644, |
| 376 | ) |
| 377 | except FileExistsError: |
| 378 | continue |
| 379 | try: |
| 380 | with os.fdopen(fd, "wb") as f: |
| 381 | content = render_fn(candidate) if render_fn is not None else static_content |
| 382 | f.write(content.encode("utf-8")) |
| 383 | except BaseException: |
| 384 | # Deferred rendering happens after the candidate is reserved. Do |
| 385 | # not leave an empty or partial report if rendering or writing fails. |
| 386 | try: |
| 387 | candidate.unlink(missing_ok=True) |
| 388 | except OSError: |
| 389 | pass |
| 390 | raise |
| 391 | if candidate.suffix.lower() == ".md": |
| 392 | try: |
| 393 | from lib import library_index |
| 394 | |
| 395 | save_root = candidate.parent.resolve() |
| 396 | db_path = library_index.saved_report_index_path(save_root) |
| 397 | # A scoped save must sync a per-directory index with the |
| 398 | # same paths scoped search uses; syncing the shared DB |
| 399 | # from one scope's scan would prune other scopes' rows. |
| 400 | if not _is_scoped_save_dir(save_root): |
| 401 | library_index.sync_library(save_root) |
| 402 | else: |
| 403 | library_index.sync_library(save_root, save_root / "briefings", db_path=db_path) |
| 404 | except (library_index.LibrarySearchUnavailable, OSError, sqlite3.DatabaseError): |
| 405 | # Saving research must not depend on the optional local index; |
| 406 | # `library search` reports a clear capability error on demand. |
| 407 | pass |
| 408 | return candidate |
| 409 | # Fallback: all 101 candidates existed (extremely unlikely). |
| 410 | raise RuntimeError( |
| 411 | f"save_output: could not find a unique filename after 101 attempts in {path}" |
| 412 | ) |
| 413 | |
| 414 | |
| 415 | def save_rendered_output( |
| 416 | rendered_content: str, |
| 417 | output_file: str, |
| 418 | *, |
| 419 | private: bool = False, |
| 420 | ) -> Path: |
| 421 | out_path = Path(output_file).expanduser().resolve() |
| 422 | _ensure_output_directory(out_path.parent, private=private) |
| 423 | if private and out_path.exists(): |
| 424 | out_path.chmod(0o600) |
| 425 | fd = os.open( |
| 426 | out_path, |
| 427 | os.O_CREAT | os.O_TRUNC | os.O_WRONLY, |
| 428 | 0o600 if private else 0o644, |
| 429 | ) |
| 430 | with os.fdopen(fd, "w", encoding="utf-8") as handle: |
| 431 | handle.write(rendered_content) |
| 432 | if private: |
| 433 | out_path.chmod(0o600) |
| 434 | return out_path |
| 435 | |
| 436 | |
| 437 | def _publish_metadata_path(html_path: Path) -> Path: |
| 438 | return html_path.with_name(f"{html_path.name}.publish.json") |
| 439 | |
| 440 | |
| 441 | def _write_publish_metadata(html_path: Path, publish_result: dict[str, object]) -> None: |
| 442 | payload = { |
| 443 | "url": publish_result.get("url"), |
| 444 | "site_id": publish_result.get("site_id"), |
| 445 | "status": publish_result.get("status"), |
| 446 | "published_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), |
| 447 | } |
| 448 | _publish_metadata_path(html_path).write_text(json.dumps(payload, indent=2), encoding="utf-8") |
| 449 | |
| 450 | |
| 451 | def publish_rendered_html( |
| 452 | rendered: str, |
| 453 | *, |
| 454 | password: str | None = None, |
| 455 | companion_paths: list[Path] | None = None, |
| 456 | ) -> dict[str, object]: |
| 457 | from lib import html_publish |
| 458 | |
| 459 | result = html_publish.publish_html(rendered, password=password) |
| 460 | metadata_errors: list[str] = [] |
| 461 | for path in companion_paths or []: |
| 462 | try: |
| 463 | _write_publish_metadata(path, result) |
| 464 | except OSError as exc: |
| 465 | metadata_errors.append(f"{path}: {exc}") |
| 466 | if metadata_errors: |
| 467 | result = dict(result) |
| 468 | result["_metadata_errors"] = metadata_errors |
| 469 | return result |
| 470 | |
| 471 | |
| 472 | def _publish_password_for_args( |
| 473 | args: argparse.Namespace, |
| 474 | config: dict[str, object] | None = None, |
| 475 | ) -> str | None: |
| 476 | return ( |
| 477 | args.publish_password |
| 478 | or env.read_secret_env("LAST30DAYS_PUBLISH_PASSWORD") |
| 479 | or (config or {}).get("LAST30DAYS_PUBLISH_PASSWORD") |
| 480 | or None |
| 481 | ) |
| 482 | |
| 483 | |
| 484 | def emit_output( |
| 485 | report: schema.Report, |
| 486 | emit: str, |
| 487 | fun_level: str = "medium", |
| 488 | save_path: str | None = None, |
| 489 | synthesis_md: str | None = None, |
| 490 | json_profile: str = "agent", |
| 491 | register: str = "default", |
| 492 | ) -> str: |
| 493 | if emit == "json": |
| 494 | payload = ( |
| 495 | schema.to_dict(report) |
| 496 | if json_profile == "raw" |
| 497 | else schema.to_agent_export(report) |
| 498 | ) |
| 499 | return json.dumps(payload, indent=2, sort_keys=True) |
| 500 | if emit == "html": |
| 501 | return html_render.render_html( |
| 502 | report, |
| 503 | fun_level=fun_level, |
| 504 | save_path=save_path, |
| 505 | synthesis_md=synthesis_md, |
| 506 | register=register, |
| 507 | ) |
| 508 | if emit in {"compact", "md"}: |
| 509 | return render.render_compact( |
| 510 | report, |
| 511 | fun_level=fun_level, |
| 512 | save_path=save_path, |
| 513 | register=register, |
| 514 | ) |
| 515 | if emit == "context": |
| 516 | return render.render_context(report) |
| 517 | if emit == "brief": |
| 518 | return render.render_brief(report) |
| 519 | raise SystemExit(f"Unsupported emit mode: {emit}") |
| 520 | |
| 521 | |
| 522 | def emit_comparison_output( |
| 523 | entity_reports: list[tuple[str, schema.Report]], |
| 524 | emit: str, |
| 525 | fun_level: str = "medium", |
| 526 | save_path: str | None = None, |
| 527 | synthesis_md: str | None = None, |
| 528 | json_profile: str = "agent", |
| 529 | ) -> str: |
| 530 | if emit == "json": |
| 531 | payload = { |
| 532 | "comparison": True, |
| 533 | "entities": [label for label, _ in entity_reports], |
| 534 | "reports": [ |
| 535 | { |
| 536 | "entity": label, |
| 537 | "report": ( |
| 538 | schema.to_dict(report) |
| 539 | if json_profile == "raw" |
| 540 | else schema.to_agent_export(report) |
| 541 | ), |
| 542 | } |
| 543 | for label, report in entity_reports |
| 544 | ], |
| 545 | } |
| 546 | if json_profile == "agent": |
| 547 | payload["schema_version"] = schema.AGENT_EXPORT_SCHEMA_VERSION |
| 548 | return json.dumps(payload, indent=2, sort_keys=True) |
| 549 | if emit == "html": |
| 550 | return html_render.render_html_comparison( |
| 551 | entity_reports, |
| 552 | fun_level=fun_level, |
| 553 | save_path=save_path, |
| 554 | synthesis_md=synthesis_md, |
| 555 | ) |
| 556 | if emit in {"compact", "md"}: |
| 557 | return render.render_comparison_multi( |
| 558 | entity_reports, fun_level=fun_level, save_path=save_path, |
| 559 | ) |
| 560 | if emit == "context": |
| 561 | return render.render_comparison_multi_context(entity_reports) |
| 562 | raise SystemExit(f"Unsupported emit mode: {emit}") |
| 563 | |
| 564 | |
| 565 | def comparison_topic(entity_reports: list[tuple[str, schema.Report]]) -> str: |
| 566 | return " vs ".join(label for label, _ in entity_reports) |
| 567 | |
| 568 | |
| 569 | def comparison_label_key(label: str) -> str: |
| 570 | """Normalize an entity label for duplicate detection. |
| 571 | |
| 572 | Comparison labels double as keys in the fan-out's results dict, so two |
| 573 | entities differing only in case, surrounding space, or a repeated space |
| 574 | collide there while still looking distinct on the command line. Spaces |
| 575 | are collapsed, never stripped: "Open AI" stays distinct from "OpenAI". |
| 576 | """ |
| 577 | return " ".join(label.split()).casefold() |
| 578 | |
| 579 | |
| 580 | def compute_save_path_display(save_dir: str, topic: str, suffix: str, emit: str) -> str: |
| 581 | """Compute the user-friendly save path string that will be shown in the footer. |
| 582 | |
| 583 | Uses ~ when the saved file is under the user's home directory; otherwise |
| 584 | returns the absolute path. |
| 585 | """ |
| 586 | from pathlib import Path as _Path |
| 587 | path = _Path(save_dir).expanduser().resolve() |
| 588 | slug = slugify(topic) |
| 589 | extension = "json" if emit == "json" else "html" if emit == "html" else "md" |
| 590 | raw_label = "raw-html" if emit == "html" else "raw" |
| 591 | safe_suffix = sanitize_suffix(suffix) |
| 592 | suffix_part = f"-{safe_suffix}" if safe_suffix else "" |
| 593 | raw = path / f"{slug}-{raw_label}{suffix_part}.{extension}" |
| 594 | try: |
| 595 | home = _Path.home().resolve() |
| 596 | relative = raw.relative_to(home) |
| 597 | return f"~/{relative.as_posix()}" |
| 598 | except ValueError: |
| 599 | return raw.as_posix() |
| 600 | |
| 601 | |
| 602 | def compute_output_path_display(output_file: str) -> str: |
| 603 | """Compute the user-friendly explicit output path shown in render footers.""" |
| 604 | raw = Path(output_file).expanduser().resolve() |
| 605 | try: |
| 606 | home = Path.home().resolve() |
| 607 | relative = raw.relative_to(home) |
| 608 | return f"~/{relative.as_posix()}" |
| 609 | except ValueError: |
| 610 | return raw.as_posix() |
| 611 | |
| 612 | |
| 613 | def read_synthesis_file(path: str) -> str: |
| 614 | try: |
| 615 | return Path(path).expanduser().read_text(encoding="utf-8") |
| 616 | except OSError as exc: |
| 617 | sys.stderr.write(f"[last30days] Cannot read --synthesis-file: {exc}\n") |
| 618 | raise SystemExit(2) |
| 619 | |
| 620 | |
| 621 | def _validate_save_dir(save_dir: Path | str | None) -> int | None: |
| 622 | if pipeline.is_blank_save_dir(save_dir): |
| 623 | sys.stderr.write( |
| 624 | "[last30days] --save-dir / LAST30DAYS_MEMORY_DIR cannot be whitespace-only.\n" |
| 625 | ) |
| 626 | return 2 |
| 627 | return None |
| 628 | |
| 629 | |
| 630 | def _is_scoped_save_dir(save_dir: Path | str | None) -> bool: |
| 631 | """True when ``save_dir`` is set and resolves to a dir other than DEFAULT_MEMORY_DIR.""" |
| 632 | return pipeline.is_scoped_save_dir(save_dir) |
| 633 | |
| 634 | |
| 635 | def _scoped_store_db(args: argparse.Namespace) -> Path | None: |
| 636 | """Scoped runs write findings inside the save dir, matching scoped reads.""" |
| 637 | return pipeline.scoped_store_db_path(getattr(args, "save_dir", None)) |
| 638 | |
| 639 | |
| 640 | def _research_store_enabled(args: argparse.Namespace, config: dict[str, object]) -> bool: |
| 641 | store_setting = os.environ.get("LAST30DAYS_STORE") or config.get("LAST30DAYS_STORE") or "" |
| 642 | return args.store or str(store_setting).lower() in {"1", "true", "yes"} |
| 643 | |
| 644 | |
| 645 | def _add_preflight_library_writes( |
| 646 | preflight: dict, args: argparse.Namespace, config: dict[str, object], |
| 647 | ) -> None: |
| 648 | from lib import library_index |
| 649 | |
| 650 | on_save = bool(args.preflight_report_on_save_dir and not args.save_dir) |
| 651 | save_dir = args.preflight_report_on_save_dir if on_save else args.save_dir |
| 652 | local, conditional = preflight["local_writes"], preflight["conditional_writes"] |
| 653 | context_db = None if args.mock else pipeline.library_context_index_path(config, save_dir) |
| 654 | if context_db is not None: |
| 655 | write = {"kind": "library_index_on_save" if on_save else "library_index", "path": str(context_db)} |
| 656 | (conditional if on_save else local).append(write) |
| 657 | if save_dir and not pipeline.is_blank_save_dir(save_dir) and args.emit != "html": |
| 658 | markdown_db = library_index.saved_report_index_path(Path(save_dir).expanduser().resolve()) |
| 659 | if markdown_db != context_db: |
| 660 | conditional.append({"kind": "library_index_on_markdown_save", "path": str(markdown_db)}) |
| 661 | |
| 662 | |
| 663 | def _add_preflight_research_writes( |
| 664 | preflight: dict, args: argparse.Namespace, config: dict[str, object], |
| 665 | ) -> None: |
| 666 | if args.preflight_engine_cache_dir: |
| 667 | preflight["conditional_writes"].append({ |
| 668 | "kind": "engine_cache_on_first_use", "path": args.preflight_engine_cache_dir, |
| 669 | }) |
| 670 | if args.no_research_persistence: |
| 671 | return |
| 672 | if ( |
| 673 | env.hosted_backend_configured() |
| 674 | and not config.get("_CORPUS_DIRS") |
| 675 | and not args.mock and not args.record_fixtures and not args.deep_research |
| 676 | and (args.perplexity_search_type is None or not config.get("PERPLEXITY_API_KEY")) |
| 677 | ): |
| 678 | return |
| 679 | if not args.mock and not args.record_fixtures and not args.cached_report: |
| 680 | from lib import rust_accel |
| 681 | if rust_accel.would_auto_install_on_run(): |
| 682 | preflight["conditional_writes"].append({ |
| 683 | "kind": "native_core_on_first_run", |
| 684 | "path": str(rust_accel.install_bin_path()), |
| 685 | }) |
| 686 | mcp_preflight = args.preflight_engine_cache_dir is not None |
| 687 | research_writes = preflight["conditional_writes" if mcp_preflight else "local_writes"] |
| 688 | kind_suffix = "_on_save" if mcp_preflight else "" |
| 689 | if env.CONFIG_DIR is not None: |
| 690 | for filename in ("last-run.json", "last-report.json"): |
| 691 | research_writes.append({ |
| 692 | "kind": "research_cache" + kind_suffix, "path": str(env.CONFIG_DIR / filename), |
| 693 | }) |
| 694 | if config.get("_CORPUS_DIRS"): |
| 695 | research_writes.append({ |
| 696 | "kind": "corpus_cache" + kind_suffix, "path": str(env.CONFIG_DIR / corpus.CACHE_FILENAME), |
| 697 | }) |
| 698 | _add_preflight_library_writes(preflight, args, config) |
| 699 | if not _research_store_enabled(args, config): |
| 700 | return |
| 701 | import store |
| 702 | |
| 703 | store_args = argparse.Namespace(save_dir=args.preflight_report_on_save_dir) if mcp_preflight else args |
| 704 | db_path = _scoped_store_db(store_args) or store.DB_PATH |
| 705 | research_writes.append({"kind": "research_store" + kind_suffix, "path": str(db_path)}) |
| 706 | |
| 707 | |
| 708 | def persist_report(report: schema.Report, store_db: Path | None = None) -> dict[str, int]: |
| 709 | import store |
| 710 | |
| 711 | private_corpus = _report_has_private_corpus(report) |
| 712 | with store.scoped_db(store_db): |
| 713 | if private_corpus: |
| 714 | store.ensure_private_db_files() |
| 715 | store.init_db() |
| 716 | if private_corpus: |
| 717 | store.ensure_private_db_files() |
| 718 | topic_row = store.add_topic(report.topic, update_existing=False) |
| 719 | topic_id = topic_row["id"] |
| 720 | source_mode = ",".join(sorted(report.items_by_source)) or "v3" |
| 721 | run_id = store.record_run(topic_id, source_mode=source_mode, status="running") |
| 722 | try: |
| 723 | findings = store.findings_from_report(report) |
| 724 | if private_corpus: |
| 725 | store.ensure_private_db_files() |
| 726 | counts = store.store_findings(run_id, topic_id, findings) |
| 727 | store.update_run( |
| 728 | run_id, |
| 729 | status="completed", |
| 730 | findings_new=counts["new"], |
| 731 | findings_updated=counts["updated"], |
| 732 | ) |
| 733 | return counts |
| 734 | except Exception as exc: |
| 735 | store.update_run(run_id, status="failed", error_message=str(exc)[:500]) |
| 736 | raise |
| 737 | finally: |
| 738 | if private_corpus: |
| 739 | store.ensure_private_db_files() |
| 740 | |
| 741 | |
| 742 | def build_parser() -> argparse.ArgumentParser: |
| 743 | parser = argparse.ArgumentParser( |
| 744 | description="Research a topic across live social, market, and grounded web sources.", |
| 745 | allow_abbrev=False, |
| 746 | ) |
| 747 | parser.add_argument("topic", nargs="*", help="Research topic") |
| 748 | parser.add_argument("--research-only", action="store_true", |
| 749 | help="Treat the topic as research text, never as an administrative command") |
| 750 | parser.add_argument("--emit", default="compact", choices=["compact", "json", "context", "md", "html", "brief"]) |
| 751 | parser.add_argument( |
| 752 | "--register", |
| 753 | choices=registers.REGISTER_NAMES, |
| 754 | default=None, |
| 755 | help="Audience synthesis preset for the standard brief (default, exec, dev, creator, eli5)", |
| 756 | ) |
| 757 | clarify_group = parser.add_mutually_exclusive_group() |
| 758 | clarify_group.add_argument( |
| 759 | "--clarify-angle", |
| 760 | default=None, |
| 761 | help="Hosted backend only: answer its clarification with this angle (an option's query)", |
| 762 | ) |
| 763 | clarify_group.add_argument( |
| 764 | "--clarify-broadly", |
| 765 | action="store_true", |
| 766 | help="Hosted backend only: answer its clarification by running the topic as asked", |
| 767 | ) |
| 768 | parser.add_argument( |
| 769 | "--json-profile", |
| 770 | default="agent", |
| 771 | choices=["agent", "raw"], |
| 772 | help="JSON export profile for --emit=json (default: agent)", |
| 773 | ) |
| 774 | parser.add_argument("--require-local-report", action="store_true", help=argparse.SUPPRESS) |
| 775 | parser.add_argument("--search", help="Comma-separated source list") |
| 776 | parser.add_argument("--quick", action="store_true", help="Lower-latency retrieval profile") |
| 777 | parser.add_argument("--deep", action="store_true", help="Higher-recall retrieval profile") |
| 778 | freshness_group = parser.add_mutually_exclusive_group() |
| 779 | freshness_group.add_argument( |
| 780 | "--verify-freshness", |
| 781 | action="store_true", |
| 782 | default=None, |
| 783 | help="Re-check source-grounded claims after research, or verify the cached report when no topic is supplied", |
| 784 | ) |
| 785 | freshness_group.add_argument( |
| 786 | "--no-verify-freshness", |
| 787 | dest="verify_freshness", |
| 788 | action="store_false", |
| 789 | help="Disable freshness verification configured by LAST30DAYS_VERIFY_FRESHNESS", |
| 790 | ) |
| 791 | parser.add_argument( |
| 792 | "--drill", |
| 793 | metavar="TARGET", |
| 794 | help="Deep follow-up on a cluster from the fresh last-report.json cache", |
| 795 | ) |
| 796 | parser.add_argument( |
| 797 | "--followup-topic", |
| 798 | metavar="TOPIC", |
| 799 | help="Require the cached report for a drill or post-run freshness check to match TOPIC", |
| 800 | ) |
| 801 | parser.add_argument( |
| 802 | "--followup-run", |
| 803 | metavar="ID", |
| 804 | help="Require the cache ID reported by the original research or most recent drill", |
| 805 | ) |
| 806 | parser.add_argument( |
| 807 | "--discover", |
| 808 | metavar="DOMAIN", |
| 809 | nargs="?", |
| 810 | const="", |
| 811 | default=None, |
| 812 | help=( |
| 813 | "Sweep river listings and rank the topics accelerating in a domain; " |
| 814 | "each survivor gets a full research pass. Bare --discover (no domain) " |
| 815 | "runs global trending across every feed's hot list" |
| 816 | ), |
| 817 | ) |
| 818 | parser.add_argument( |
| 819 | "--discover-shallow", |
| 820 | action="store_true", |
| 821 | help=( |
| 822 | "Skip the per-topic research pass during --discover: rank on listing " |
| 823 | "evidence only (faster, thinner; the confidence floor still applies)" |
| 824 | ), |
| 825 | ) |
| 826 | parser.add_argument( |
| 827 | "--nominate-only", |
| 828 | action="store_true", |
| 829 | help=( |
| 830 | "Leg 1 of the host-judged discovery protocol: sweep, write the " |
| 831 | "nominations bundle for host judgment, and stop (no judging, no " |
| 832 | "enrichment). Requires --discover" |
| 833 | ), |
| 834 | ) |
| 835 | parser.add_argument( |
| 836 | "--judgments", |
| 837 | metavar="PATH", |
| 838 | help=( |
| 839 | "Leg 2 of the discovery protocol: resume from the nominations " |
| 840 | "bundle, applying the host judgments file at PATH. Requires " |
| 841 | "--discover" |
| 842 | ), |
| 843 | ) |
| 844 | parser.add_argument( |
| 845 | "--finalize", |
| 846 | action="store_true", |
| 847 | help=( |
| 848 | "Leg 3 of the discovery protocol: apply host angles, render the " |
| 849 | "final discovery brief, and record the topic queue. Requires " |
| 850 | "--discover" |
| 851 | ), |
| 852 | ) |
| 853 | parser.add_argument( |
| 854 | "--angles", |
| 855 | metavar="PATH", |
| 856 | help=( |
| 857 | "Optional host angles file for --discover --finalize (omitting it " |
| 858 | "ships the brief without angle lines)" |
| 859 | ), |
| 860 | ) |
| 861 | parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging") |
| 862 | parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures") |
| 863 | parser.add_argument( |
| 864 | "--record-fixtures", |
| 865 | metavar="DIR", |
| 866 | help=argparse.SUPPRESS, |
| 867 | ) |
| 868 | parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability") |
| 869 | parser.add_argument( |
| 870 | "--include-research-backend", action="store_true", |
| 871 | help="Include the selected research backend in --diagnose JSON", |
| 872 | ) |
| 873 | parser.add_argument("--preflight", action="store_true", |
| 874 | help="Print a safe human-readable permission preflight") |
| 875 | parser.add_argument("--welcome", action="store_true", |
| 876 | help="Print the first-run welcome text (engine-owned; relay verbatim)") |
| 877 | parser.add_argument("--preflight-report-on-save-dir", help=argparse.SUPPRESS) |
| 878 | parser.add_argument("--preflight-engine-cache-dir", help=argparse.SUPPRESS) |
| 879 | parser.add_argument("--no-browser-cookies", action="store_true", |
| 880 | help="Disable browser-cookie extraction even when FROM_BROWSER is configured") |
| 881 | parser.add_argument("--save-dir", help="Optional directory for saving the rendered output") |
| 882 | parser.add_argument("--no-research-persistence", action="store_true", help=argparse.SUPPRESS) |
| 883 | parser.add_argument( |
| 884 | "--resolve-save-dir", action="store_true", |
| 885 | help="Print the skill save directory from flags/config, then exit without research", |
| 886 | ) |
| 887 | parser.add_argument( |
| 888 | "--resolve-browser-consent", action="store_true", |
| 889 | help="Print whether an explicit browser-cookie grant is active, without reading cookies", |
| 890 | ) |
| 891 | parser.add_argument( |
| 892 | "--corpus", |
| 893 | action="append", |
| 894 | default=[], |
| 895 | metavar="DIR", |
| 896 | help="Add a local .md/.txt/.pdf directory as a private ranked source (repeatable)", |
| 897 | ) |
| 898 | parser.add_argument( |
| 899 | "--corpus-all-time", |
| 900 | action="store_true", |
| 901 | help="Include matching corpus files older than the research window", |
| 902 | ) |
| 903 | parser.add_argument("--output", help="Optional exact file path for saving the rendered output") |
| 904 | parser.add_argument("--synthesis-file", help="Markdown synthesis to embed in --emit=html output") |
| 905 | parser.add_argument("--cached-report", action="store_true", |
| 906 | help="Render --emit=html --synthesis-file from cached research only, without replaying temporary plans") |
| 907 | parser.add_argument("--publish-html", action="store_true", |
| 908 | help="Publish --emit=html output to ht-ml.app (explicit opt-in; public by default)") |
| 909 | parser.add_argument("--publish", action="store_true", |
| 910 | help="With 'library feed', publish the HTML index and briefs (explicit opt-in; public by default); feed.xml remains local") |
| 911 | parser.add_argument("--publish-password", |
| 912 | help="Optional shared password for --publish-html or 'library feed --publish'; prefer LAST30DAYS_PUBLISH_PASSWORD to avoid exposing secrets in process lists") |
| 913 | parser.add_argument("--store", action="store_true", help="Persist ranked findings to the SQLite research store") |
| 914 | parser.add_argument("--x-handle", help="X handle for targeted supplemental search") |
| 915 | parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)") |
| 916 | parser.add_argument( |
| 917 | "--ticker", |
| 918 | metavar="SYMBOL:COMPANY[,SYMBOL:COMPANY]", |
| 919 | help=( |
| 920 | "Stock ticker of the listed company behind the topic, with that company's " |
| 921 | "name, as the hosting model found it by web search (e.g., \"NVDA:Nvidia\", " |
| 922 | "or \"TSLA:Tesla,SPCX:SpaceX\" for a person who leads two). At most two " |
| 923 | "pairs. Each is checked against Yahoo Finance before a share-price line is " |
| 924 | "shown; when it is passed, no other ticker lookup is used." |
| 925 | ), |
| 926 | ) |
| 927 | parser.add_argument( |
| 928 | "--company", |
| 929 | metavar="NAME[:SITE][,NAME[:SITE]]", |
| 930 | help=( |
| 931 | "The company behind the topic, listed or not, with its own website, as " |
| 932 | "the hosting model found them by web search: the company a person leads " |
| 933 | "or founded (Palmer Luckey: \"Anduril:anduril.com\"), or the maker of a " |
| 934 | "product. At most two; the jobs lane reads the board of the first that " |
| 935 | "has one. The site may be left out (\"Anduril\")." |
| 936 | ), |
| 937 | ) |
| 938 | parser.add_argument( |
| 939 | "--jobs-board", |
| 940 | dest="jobs_board", |
| 941 | metavar="URL", |
| 942 | help=( |
| 943 | "The company's job-board URL as the hosting model found it by web search " |
| 944 | "(e.g., https://job-boards.greenhouse.io/andurilindustries; Greenhouse, " |
| 945 | "Ashby, Lever, Workable, SmartRecruiters or Workday). The engine reads " |
| 946 | "that board and gives a digest only when the board names the company or " |
| 947 | "the official site links to it." |
| 948 | ), |
| 949 | ) |
| 950 | parser.add_argument( |
| 951 | "--official-site", |
| 952 | metavar="DOMAIN", |
| 953 | help=( |
| 954 | "The topic's own website (e.g., typesafe.ai). The engine reads the X and " |
| 955 | "GitHub accounts the homepage links and uses them when --x-handle / " |
| 956 | "--github-user are not set. Keyless." |
| 957 | ), |
| 958 | ) |
| 959 | parser.add_argument( |
| 960 | "--no-x-handle", |
| 961 | metavar="REASON", |
| 962 | help=( |
| 963 | "Record that the topic has no resolvable X account, and why (e.g., " |
| 964 | "\"official site links no X account; x.com-filtered search found none\"). " |
| 965 | "Satisfies the agent-hosted X handle decision check without --x-handle." |
| 966 | ), |
| 967 | ) |
| 968 | parser.add_argument( |
| 969 | "--x-posts", |
| 970 | dest="x_posts", |
| 971 | metavar="PATH", |
| 972 | help=( |
| 973 | "Path to a last30days-x-posts/1 JSON envelope of posts the hosting " |
| 974 | "model fetched through its X connector; replaces the engine's X " |
| 975 | "fetch for this run. A file path only (never inline JSON); on a " |
| 976 | "comparison run use the per-entity x_posts field of --competitors-plan." |
| 977 | ), |
| 978 | ) |
| 979 | parser.add_argument( |
| 980 | "--reddit-threads", |
| 981 | dest="reddit_threads", |
| 982 | metavar="PATH", |
| 983 | help=( |
| 984 | "Path to a last30days-reddit-threads/1 JSON envelope of Reddit " |
| 985 | "thread URLs or ids the hosting model found with its own web " |
| 986 | "search ('-' reads stdin). Only each entry's url or id is read; " |
| 987 | "the engine rehydrates every thread and holds it to the window " |
| 988 | "and the topic. At most 50 threads; single-topic runs only." |
| 989 | ), |
| 990 | ) |
| 991 | parser.add_argument( |
| 992 | "--shortform-urls", |
| 993 | dest="shortform_urls", |
| 994 | metavar="PATH", |
| 995 | help=( |
| 996 | "Path to a last30days-shortform-urls/1 JSON envelope of TikTok and " |
| 997 | "Instagram post URLs and TikTok creator profile URLs the hosting " |
| 998 | "model found with its own web search ('-' reads stdin). Only each " |
| 999 | "entry's url is read; used only by the keyless TikTok/Instagram " |
| 1000 | "lane (no ScrapeCreators key, or credits exhausted), which dates, " |
| 1001 | "hydrates and topic-checks every post itself. At most 40 URLs; " |
| 1002 | "single-topic runs only." |
| 1003 | ), |
| 1004 | ) |
| 1005 | parser.add_argument("--web-backend", default="auto", |
| 1006 | choices=["auto", "brave", "exa", "serper", "parallel", "parallel-mcp", "keyless", "none"], |
| 1007 | help="Web search backend (default: auto; parallel-mcp explicitly opts into the " |
| 1008 | "anonymous hosted MCP; keyless forces the zero-key floor)") |
| 1009 | parser.add_argument("--perplexity-search-type", choices=["web", "fast"], |
| 1010 | help="Search backend for direct Perplexity Search API and Agent web_search; overrides LAST30DAYS_PERPLEXITY_SEARCH_TYPE. Does not enable the paid source or select an Agent preset.") |
| 1011 | parser.add_argument("--deep-research", action="store_true", |
| 1012 | help="Use at most one Perplexity Deep Research run. Direct PERPLEXITY_API_KEY uses the Agent API background path; OPENROUTER_API_KEY keeps the synchronous Sonar fallback; cannot be combined with competitor or vs-mode.") |
| 1013 | parser.add_argument("--hiring-signals", action="store_true", |
| 1014 | help="Analyze public jobs/careers postings as evidence-backed company focus signals.") |
| 1015 | parser.add_argument("--plan", help="JSON query plan (skips internal LLM planner). Can be a JSON string, a file path, or - for stdin.") |
| 1016 | parser.add_argument("--save-suffix", help="Suffix for saved output filename (e.g., 'gemini' → kanye-west-raw-gemini.md)") |
| 1017 | parser.add_argument("--subreddits", help="Comma-separated broad/category subreddit names to search (e.g., SaaS,Entrepreneur)") |
| 1018 | parser.add_argument("--dedicated-subreddits", help="Comma-separated entity-home subreddit names (e.g., Kanye,WestSubEver). Pulled in full (top+hot+new) and exempt from the relevance floor since the whole sub is the topic.") |
| 1019 | parser.add_argument("--devto-tags", help="Comma-separated dev.to tags, lowercase alphanumeric (e.g., claudecode,ai)") |
| 1020 | parser.add_argument("--tiktok-hashtags", help="Comma-separated TikTok hashtags without # (e.g., tella,screenrecording)") |
| 1021 | parser.add_argument("--tiktok-creators", help="Comma-separated TikTok creator handles (e.g., TellaHQ,taborplace)") |
| 1022 | parser.add_argument("--ig-creators", help="Comma-separated Instagram creator handles (e.g., tella.tv,laborstories)") |
| 1023 | parser.add_argument( |
| 1024 | "--days", |
| 1025 | "--lookback-days", |
| 1026 | dest="lookback_days", |
| 1027 | type=int, |
| 1028 | default=None, |
| 1029 | help="Number of days to look back for research (default: 30, watchlist uses 90)", |
| 1030 | ) |
| 1031 | parser.add_argument( |
| 1032 | "--as-of", |
| 1033 | dest="as_of_date", |
| 1034 | type=parse_as_of_date_arg, |
| 1035 | help=( |
| 1036 | "End date for the lookback window in YYYY-MM-DD format. " |
| 1037 | "When set, --days looks back from this date instead of today." |
| 1038 | ), |
| 1039 | ) |
| 1040 | parser.add_argument("--max-results", dest="max_results", type=int, |
| 1041 | help="Override the final ranked-pool cap (pool_limit/rerank_limit) from the depth profile. " |
| 1042 | "Use for high-volume topics where the default (deep=60) under-covers. See issue #716.") |
| 1043 | parser.add_argument( |
| 1044 | "--source", |
| 1045 | dest="harvest_source", |
| 1046 | default=None, |
| 1047 | help="Transcript source for 'library harvest' (auto, all, claude, codex, antigravity, gemini, cursor)", |
| 1048 | ) |
| 1049 | parser.add_argument( |
| 1050 | "--since", |
| 1051 | dest="harvest_since", |
| 1052 | default=None, |
| 1053 | help="Only harvest finished briefs on or after YYYY-MM-DD (for 'library harvest')", |
| 1054 | ) |
| 1055 | parser.add_argument( |
| 1056 | "--dry-run", |
| 1057 | dest="dry_run", |
| 1058 | action="store_true", |
| 1059 | help="Preview 'library harvest' without writing files", |
| 1060 | ) |
| 1061 | parser.add_argument("--max-per-source", dest="max_per_source", type=int, |
| 1062 | help="Override the per-stream cap (per_stream_limit) applied to each (source, subquery) before " |
| 1063 | "pooling. Raising it increases unique-item yield when one source has many relevant items. " |
| 1064 | "See issue #716.") |
| 1065 | parser.add_argument("--max-source-fetches", dest="max_source_fetches", type=int, |
| 1066 | help="Override the per-source fetch cap (MAX_SOURCE_FETCHES, default x=2) that limits how many " |
| 1067 | "subqueries actually fetch a capped source. Raise it so every X subquery in a multi-angle " |
| 1068 | "--plan runs instead of just the first two. See issue #716.") |
| 1069 | parser.add_argument("--auto-resolve", action="store_true", |
| 1070 | help="Use web search to discover subreddits/handles before planning (for platforms without WebSearch)") |
| 1071 | parser.add_argument("--github-user", help="GitHub username for person-mode search (e.g., steipete)") |
| 1072 | parser.add_argument("--github-repo", help="Comma-separated owner/repo for project-mode search (e.g., openclaw/openclaw,paperclipai/paperclip)") |
| 1073 | parser.add_argument( |
| 1074 | "--employer", |
| 1075 | metavar="NAME[:DOMAIN]", |
| 1076 | help=( |
| 1077 | "Person run: the person's current employer, as \"Name\" or \"Name:domain\" " |
| 1078 | "(e.g., \"Northwind Freight:northwind.example\"). Its name and domain become " |
| 1079 | "identity anchors. Not --company, which researches a company the person leads." |
| 1080 | ), |
| 1081 | ) |
| 1082 | parser.add_argument( |
| 1083 | "--linkedin", |
| 1084 | metavar="URL", |
| 1085 | help=( |
| 1086 | "Person run: the person's LinkedIn profile URL " |
| 1087 | "(https://www.linkedin.com/in/<name>), trusted as an identity anchor." |
| 1088 | ), |
| 1089 | ) |
| 1090 | parser.add_argument( |
| 1091 | "--email", |
| 1092 | metavar="ADDR", |
| 1093 | help=( |
| 1094 | "Person run: the person's email address. A work domain becomes an identity " |
| 1095 | "anchor; a personal-mail domain (gmail and similar) does not. Never logged." |
| 1096 | ), |
| 1097 | ) |
| 1098 | parser.add_argument( |
| 1099 | "--trustpilot-domain", |
| 1100 | help=( |
| 1101 | "Trustpilot review-page domain for the topic (e.g., www.thriftbooks.com). " |
| 1102 | "Used verbatim, bypasses the brand-shape gate, and auto-activates the " |
| 1103 | "opt-in Trustpilot source for this run (unless EXCLUDE_SOURCES=trustpilot). " |
| 1104 | "Find the domain with `trustpilot-pp-cli search '<name>'`." |
| 1105 | ), |
| 1106 | ) |
| 1107 | parser.add_argument( |
| 1108 | "--amazon-query", |
| 1109 | help=( |
| 1110 | "Product keyword the amazon source searches, when that source is active. " |
| 1111 | "Defaults to the topic. Supply it whenever the topic is not the product: " |
| 1112 | "a person topic searches their company's product line " |
| 1113 | "(--amazon-query='June Oven'), and a brand searches brand-plus-category " |
| 1114 | "(--amazon-query='Weber grill', not 'Weber' -- a bare brand keyword lands " |
| 1115 | "on an ad-heavy page that can miss the brand's own bestsellers). " |
| 1116 | "Requires the brightdata CLI on PATH and logged in." |
| 1117 | ), |
| 1118 | ) |
| 1119 | parser.add_argument( |
| 1120 | "--meta-ads-page", |
| 1121 | help=( |
| 1122 | "Meta Ad Library page id for the topic's advertiser, when the meta_ads " |
| 1123 | "source is active. Skips name-based page resolution and its discovery " |
| 1124 | "credit. Accepts a bare numeric page id (e.g. 123456789012345) or an Ad " |
| 1125 | "Library URL carrying view_all_page_id. A facebook.com vanity URL is not " |
| 1126 | "a page id and is rejected. Use it when a brand advertises under product " |
| 1127 | "names, or when resolution picked the wrong company." |
| 1128 | ), |
| 1129 | ) |
| 1130 | parser.add_argument( |
| 1131 | "--telegram-sources", |
| 1132 | help=( |
| 1133 | "Comma-separated list of public Telegram channel handles or t.me URLs. " |
| 1134 | "Auto-activates the opt-in Telegram source for this run. " |
| 1135 | "Accepts: bare handle (aipost), @handle (@aipost), " |
| 1136 | "t.me URL (https://t.me/aipost), or preview URL (https://t.me/s/aipost). " |
| 1137 | "Rejects joinchat links and numeric -100 supergroup IDs." |
| 1138 | ), |
| 1139 | ) |
| 1140 | parser.add_argument( |
| 1141 | "--competitors", |
| 1142 | nargs="?", |
| 1143 | const=2, |
| 1144 | type=int, |
| 1145 | default=None, |
| 1146 | metavar="N", |
| 1147 | help="Auto-discover N competitor entities and fan out last30days across all of them as a comparison (default N=2 → 3-way: original + 2 peers; range 1..6). Use --competitors-list to override discovery.", |
| 1148 | ) |
| 1149 | parser.add_argument( |
| 1150 | "--competitors-list", |
| 1151 | dest="competitors_list", |
| 1152 | help="Comma-separated competitor entities to skip discovery (e.g., 'Anthropic,xAI,Google Gemini'). Implies --competitors.", |
| 1153 | ) |
| 1154 | parser.add_argument( |
| 1155 | "--polymarket-keywords", |
| 1156 | dest="polymarket_keywords", |
| 1157 | help=( |
| 1158 | "Comma-separated keywords that Polymarket market titles must match " |
| 1159 | "to be included. Use for ambiguous single-token topics like 'Warriors' " |
| 1160 | "(nba,gsw,golden-state) to filter out Glasgow Warriors rugby, Honor " |
| 1161 | "of Kings Rogue Warriors, etc. When omitted, Polymarket returns all " |
| 1162 | "matching markets — so expect cross-entity noise on generic topics." |
| 1163 | ), |
| 1164 | ) |
| 1165 | parser.add_argument( |
| 1166 | "--competitors-plan", |
| 1167 | dest="competitors_plan", |
| 1168 | help=( |
| 1169 | "JSON mapping of per-entity Step 0.55 targeting for competitor / vs-mode " |
| 1170 | "sub-runs. Schema: {entity_name: {x_handle?, x_related?, subreddits?, " |
| 1171 | "github_user?, github_repos?, context?}}. Accepts inline JSON or a file " |
| 1172 | "path. Implies --competitors. Preferred over --competitors-list when the " |
| 1173 | "hosting model has already resolved per-entity handles and subs." |
| 1174 | ), |
| 1175 | ) |
| 1176 | return parser |
| 1177 | |
| 1178 | |
| 1179 | def parse_competitors_plan(raw: str | None) -> dict[str, dict]: |
| 1180 | """Parse a --competitors-plan argument into a {entity_name_lower: plan_entry} dict. |
| 1181 | |
| 1182 | Accepts inline JSON or a file path. Returns {} on None/empty. |
| 1183 | Validation: top-level must be a dict; each value must be a dict. Unknown fields |
| 1184 | in entry values log a warning but do not abort. Invalid JSON or non-dict shape |
| 1185 | raises SystemExit(2) with a clear stderr message. |
| 1186 | """ |
| 1187 | if not raw: |
| 1188 | return {} |
| 1189 | plan_str = raw |
| 1190 | if os.path.isfile(plan_str): |
| 1191 | try: |
| 1192 | with open(plan_str, encoding="utf-8") as f: |
| 1193 | plan_str = f.read() |
| 1194 | except (OSError, UnicodeDecodeError) as exc: |
| 1195 | sys.stderr.write(f"[CompetitorsPlan] Cannot read plan file: {exc}\n") |
| 1196 | raise SystemExit(2) |
| 1197 | try: |
| 1198 | parsed = json.loads(plan_str) |
| 1199 | except json.JSONDecodeError as exc: |
| 1200 | sys.stderr.write(f"[CompetitorsPlan] Invalid JSON: {exc}\n") |
| 1201 | raise SystemExit(2) |
| 1202 | if not isinstance(parsed, dict): |
| 1203 | sys.stderr.write( |
| 1204 | f"[CompetitorsPlan] Top-level must be a dict of " |
| 1205 | f"{{entity: {{targeting}}}}, got {type(parsed).__name__}\n" |
| 1206 | ) |
| 1207 | raise SystemExit(2) |
| 1208 | known_fields = { |
| 1209 | "x_handle", "x_related", "subreddits", |
| 1210 | "github_user", "github_repos", "trustpilot_domain", "context", |
| 1211 | "x_posts", "polymarket_hints", |
| 1212 | } |
| 1213 | normalized: dict[str, dict] = {} |
| 1214 | for entity, entry in parsed.items(): |
| 1215 | if not isinstance(entry, dict): |
| 1216 | sys.stderr.write( |
| 1217 | f"[CompetitorsPlan] Entry for {entity!r} must be a dict, " |
| 1218 | f"got {type(entry).__name__}; skipping.\n" |
| 1219 | ) |
| 1220 | continue |
| 1221 | unknown = set(entry.keys()) - known_fields |
| 1222 | if unknown: |
| 1223 | sys.stderr.write( |
| 1224 | f"[CompetitorsPlan] Unknown fields in {entity!r}: " |
| 1225 | f"{sorted(unknown)}; ignoring.\n" |
| 1226 | ) |
| 1227 | normalized[entity.strip().lower()] = { |
| 1228 | **{k: v for k, v in entry.items() if k in known_fields}, |
| 1229 | "_name": entity.strip(), |
| 1230 | } |
| 1231 | if "polymarket_hints" in entry: |
| 1232 | from lib import planner as _plan_validator |
| 1233 | try: |
| 1234 | hints = _plan_validator.polymarket_hints(entry["polymarket_hints"]) |
| 1235 | except ValueError as exc: |
| 1236 | sys.stderr.write(f"[CompetitorsPlan] Entry for {entity!r}: {exc}\n") |
| 1237 | raise SystemExit(2) |
| 1238 | normalized[entity.strip().lower()]["polymarket_hints"] = hints |
| 1239 | return normalized |
| 1240 | |
| 1241 | |
| 1242 | def subrun_kwargs_for( |
| 1243 | entity: str, |
| 1244 | plan_entry: dict, |
| 1245 | *, |
| 1246 | resolved: dict, |
| 1247 | ) -> dict: |
| 1248 | """Build an explicit per-entity kwargs dict for pipeline.run(). |
| 1249 | |
| 1250 | Plan values win over auto_resolve values. Returns keys for all per-entity |
| 1251 | targeting flags so callers never fall through to closure defaults. |
| 1252 | |
| 1253 | This helper is the single source of truth for sub-run kwargs — main-topic |
| 1254 | flags can only leak if a caller bypasses it. |
| 1255 | """ |
| 1256 | def _choose(plan_key: str, resolved_key: str | None = None): |
| 1257 | if plan_key in plan_entry and plan_entry[plan_key]: |
| 1258 | return plan_entry[plan_key] |
| 1259 | if resolved_key is not None and resolved.get(resolved_key): |
| 1260 | return resolved[resolved_key] |
| 1261 | return None |
| 1262 | |
| 1263 | x_handle = _choose("x_handle", "x_handle") |
| 1264 | if isinstance(x_handle, str): |
| 1265 | x_handle = x_handle.lstrip("@") or None |
| 1266 | |
| 1267 | subreddits = _choose("subreddits", "subreddits") |
| 1268 | if isinstance(subreddits, list): |
| 1269 | subreddits = [s.strip().removeprefix("r/") for s in subreddits if s.strip()] or None |
| 1270 | |
| 1271 | x_related = plan_entry.get("x_related") |
| 1272 | if isinstance(x_related, list): |
| 1273 | x_related = [h.strip().lstrip("@") for h in x_related if h.strip()] or None |
| 1274 | else: |
| 1275 | x_related = None |
| 1276 | |
| 1277 | github_user = _choose("github_user", "github_user") |
| 1278 | if isinstance(github_user, str): |
| 1279 | github_user = github_user.lstrip("@").lower() or None |
| 1280 | |
| 1281 | github_repos = _choose("github_repos", "github_repos") |
| 1282 | if isinstance(github_repos, list): |
| 1283 | github_repos = [r.strip() for r in github_repos if r.strip() and "/" in r.strip()] or None |
| 1284 | |
| 1285 | trustpilot_domain = _choose("trustpilot_domain", "trustpilot_domain") |
| 1286 | if isinstance(trustpilot_domain, str): |
| 1287 | trustpilot_domain = trustpilot_domain.strip() or None |
| 1288 | # Provenance: a plan-supplied domain is user-set (verbatim-final); one that |
| 1289 | # only came from auto_resolve is a hint that retries via search on a miss. |
| 1290 | trustpilot_domain_is_hint = bool( |
| 1291 | trustpilot_domain and not plan_entry.get("trustpilot_domain") |
| 1292 | ) |
| 1293 | |
| 1294 | context = plan_entry.get("context") or resolved.get("context") or "" |
| 1295 | |
| 1296 | return { |
| 1297 | "x_handle": x_handle, |
| 1298 | "x_related": x_related, |
| 1299 | "subreddits": subreddits, |
| 1300 | "github_user": github_user, |
| 1301 | "github_repos": github_repos, |
| 1302 | "trustpilot_domain": trustpilot_domain, |
| 1303 | "_trustpilot_domain_is_hint": trustpilot_domain_is_hint, |
| 1304 | "_context": context, |
| 1305 | } |
| 1306 | |
| 1307 | |
| 1308 | COMPETITORS_MIN = competitors_mod.COMPETITORS_MIN |
| 1309 | COMPETITORS_MAX = competitors_mod.COMPETITORS_MAX |
| 1310 | COMPETITORS_DEFAULT = competitors_mod.COMPETITORS_DEFAULT |
| 1311 | |
| 1312 | |
| 1313 | # The lanes that use the resolved company. With every one of them in |
| 1314 | # EXCLUDE_SOURCES nothing reads the answer, so the topic is not sent. |
| 1315 | _COMPANY_LANES = frozenset({yahoo_finance.SOURCE, "jobs", patents.SOURCE}) |
| 1316 | |
| 1317 | |
| 1318 | def _resolved_company( |
| 1319 | entity: str, *, mock: bool, config: dict, host_ticker: bool = False, |
| 1320 | patent_lane: bool = False, |
| 1321 | ) -> dict: |
| 1322 | """Company fields for one entity's ``resolved`` artifact. Mock runs, and |
| 1323 | runs that exclude every lane the company feeds, make no request. |
| 1324 | |
| 1325 | ``patent_lane`` says this run would search the entity's patent filings. |
| 1326 | Only the main topic of some runs is (see ``_patent_lane_wanted``); for |
| 1327 | every other entity the patent lane reads nothing, so it does not count |
| 1328 | among the lanes that must be excluded, and the company's other names, |
| 1329 | which only that lane reads, are not asked for. |
| 1330 | |
| 1331 | When the Wikidata lookup failed (not when it answered with nothing), |
| 1332 | Yahoo's symbol search is asked for the topic instead, and |
| 1333 | ``company_lookup`` says how that went. When Wikidata answered with |
| 1334 | nothing and ``EXA_API_KEY`` is set, an official-site search can still |
| 1335 | fill ``company`` and ``company_site``. |
| 1336 | |
| 1337 | With ``host_ticker`` the host passed ``--ticker``, which is then the only |
| 1338 | ticker source: Wikidata is asked for the company and its site but not for |
| 1339 | a listing, and a failed lookup is not followed by Yahoo's symbol search.""" |
| 1340 | lanes = _COMPANY_LANES if patent_lane else _COMPANY_LANES - {patents.SOURCE} |
| 1341 | if mock or lanes <= env.exclude_sources(config): |
| 1342 | return {} |
| 1343 | if host_ticker: |
| 1344 | return dict( |
| 1345 | company_resolve.resolve_company( |
| 1346 | entity, listing=False, names=patent_lane, config=config, |
| 1347 | ) |
| 1348 | ) |
| 1349 | company = company_resolve.resolve_company( |
| 1350 | entity, names=patent_lane, config=config, |
| 1351 | ) |
| 1352 | if isinstance(company, company_resolve.FailedLookup): |
| 1353 | backup = yahoo_finance.backup_company(entity, config) |
| 1354 | if backup is None: |
| 1355 | outcome = "backup not run" |
| 1356 | else: |
| 1357 | outcome = "yahoo backup used" if backup else "no backup match" |
| 1358 | company = {**(backup or {}), "company_lookup": f"wikidata failed; {outcome}"} |
| 1359 | if company.get("company"): |
| 1360 | ticker = f", ticker {company['ticker']}" if company.get("ticker") else "" |
| 1361 | if company.get("company_source") == yahoo_finance.BACKUP_SOURCE: |
| 1362 | ticker += " (Yahoo match)" |
| 1363 | elif company.get("company_source") == company_resolve.EXA_COMPANY_SOURCE: |
| 1364 | ticker += " (Exa site)" |
| 1365 | sys.stderr.write(f"[Resolve] {entity}: company {company['company']}{ticker}\n") |
| 1366 | if company.get("ticker") or company.get("ticker_candidates"): |
| 1367 | company["ticker_source"] = company.get("company_source") or "wikidata" |
| 1368 | return company |
| 1369 | |
| 1370 | |
| 1371 | def _patent_lane_wanted( |
| 1372 | *, comparison: bool, mock: bool, hiring_signals: bool, depth: str, config: dict, |
| 1373 | ) -> bool: |
| 1374 | """Whether this run searches the main topic's patent filings, given a |
| 1375 | company. Never for a comparison (no entity of one gets a digest), a mock |
| 1376 | run, a ``--hiring-signals`` run, quick depth, or with the lane excluded |
| 1377 | (``EXCLUDE_SOURCES`` or ``LAST30DAYS_NO_PATENT_DIGEST``).""" |
| 1378 | if comparison or mock or hiring_signals or depth == "quick": |
| 1379 | return False |
| 1380 | return not patents.is_excluded(config) |
| 1381 | |
| 1382 | |
| 1383 | def _company_for_patents(company: dict, host_names: list[str]) -> dict: |
| 1384 | """The company whose patent filings the run searches, or {} for none. |
| 1385 | |
| 1386 | The company the resolver named, with the other names it knows. When it |
| 1387 | named none, the first company the host passed with ``--company``, under |
| 1388 | that name alone. A ``--ticker`` name and ``--official-site`` are not |
| 1389 | used: neither says the topic is that company.""" |
| 1390 | if company.get("company"): |
| 1391 | return dict(company) |
| 1392 | return {"company": host_names[0]} if host_names else {} |
| 1393 | |
| 1394 | |
| 1395 | # ``--company`` takes as many names as ``--ticker`` takes pairs. |
| 1396 | MAX_HOST_COMPANIES = yahoo_finance.MAX_HOST_TICKERS |
| 1397 | |
| 1398 | |
| 1399 | def _host_companies(raw: str | None) -> list[dict[str, str]]: |
| 1400 | """The entries of a ``--company`` value, separated by commas, in the order |
| 1401 | given: ``Name`` or ``Name:site``, the shape of ``--ticker``'s pairs. |
| 1402 | |
| 1403 | The name is everything before the first colon, so it cannot hold one; |
| 1404 | the site is a bare domain or a URL, normalized to its homepage the way |
| 1405 | ``--official-site`` is. Each entry is ``name`` and ``site`` ('' when none |
| 1406 | was passed). An entry with no name is ignored, and a site that is not a |
| 1407 | domain is dropped while its name stands; each says so on stderr. Only |
| 1408 | the first ``MAX_HOST_COMPANIES`` companies are read. |
| 1409 | """ |
| 1410 | from lib import resolve as resolve_lib |
| 1411 | |
| 1412 | companies: list[dict[str, str]] = [] |
| 1413 | for entry in (raw or "").split(","): |
| 1414 | if not entry.strip(): |
| 1415 | continue |
| 1416 | name, colon, site = entry.partition(":") |
| 1417 | name = " ".join(name.split())[:80] |
| 1418 | shown = " ".join(entry.split())[:120] |
| 1419 | if not name: |
| 1420 | sys.stderr.write( |
| 1421 | f"[Resolve] --company ignoring {shown!r}: no company name before the colon\n" |
| 1422 | ) |
| 1423 | continue |
| 1424 | url = resolve_lib._official_site_url(site) if colon else "" |
| 1425 | if site.strip() and not url: |
| 1426 | sys.stderr.write( |
| 1427 | f"[Resolve] --company {name}: {' '.join(site.split())[:80]!r} is not a " |
| 1428 | "domain or URL; using the name without a site\n" |
| 1429 | ) |
| 1430 | earlier = next((c for c in companies if c["name"] == name), None) |
| 1431 | if earlier is not None: |
| 1432 | earlier["site"] = earlier["site"] or url |
| 1433 | continue |
| 1434 | companies.append({"name": name, "site": url}) |
| 1435 | if len(companies) > MAX_HOST_COMPANIES: |
| 1436 | sys.stderr.write( |
| 1437 | f"[Resolve] --company takes {MAX_HOST_COMPANIES} names; ignoring " |
| 1438 | f"{', '.join(c['name'] for c in companies[MAX_HOST_COMPANIES:])}\n" |
| 1439 | ) |
| 1440 | return companies[:MAX_HOST_COMPANIES] |
| 1441 | |
| 1442 | |
| 1443 | def _host_company_names(raw: str | None) -> list[str]: |
| 1444 | """The company names of a ``--company`` value, in the order given.""" |
| 1445 | return [company["name"] for company in _host_companies(raw)] |
| 1446 | |
| 1447 | |
| 1448 | def _company_signal( |
| 1449 | company: dict, |
| 1450 | host_tickers: list[dict] | None, |
| 1451 | official_site: str, |
| 1452 | host_names: list[str], |
| 1453 | jobs_board: str = "", |
| 1454 | ) -> str: |
| 1455 | """What makes this run about a company, or '' when nothing does. |
| 1456 | |
| 1457 | Any one is enough for the engine to add the jobs lane to a host plan that |
| 1458 | does not name it: the topic's official site, a company the host named |
| 1459 | with ``--company``, a usable ``--ticker`` pair, a ``--jobs-board`` URL |
| 1460 | (the host found a board, so the lane must read it), or the company the |
| 1461 | topic (or the person it names) resolved to. |
| 1462 | """ |
| 1463 | if (official_site or "").strip(): |
| 1464 | return "--official-site" |
| 1465 | if host_names: |
| 1466 | return "--company" |
| 1467 | if any(not pair.get("reason") and pair.get("company") for pair in host_tickers or []): |
| 1468 | return "--ticker" |
| 1469 | if (jobs_board or "").strip(): |
| 1470 | return "--jobs-board" |
| 1471 | if company.get("company"): |
| 1472 | return f"the company {company['company']}" |
| 1473 | return "" |
| 1474 | |
| 1475 | |
| 1476 | def _host_company_sites( |
| 1477 | companies: list[dict[str, str]] | list[str], *, mock: bool, config: dict, |
| 1478 | ) -> dict[str, str]: |
| 1479 | """The confirmed official site of each ``--company`` company, by name. |
| 1480 | |
| 1481 | The site the host passed with the name (``Name:site``) is used as it is: |
| 1482 | the host's web search found it, as it finds ``--official-site``. A name |
| 1483 | passed alone is asked of the company resolver (Wikidata, no key; Exa |
| 1484 | official-site fallback when ``EXA_API_KEY`` is set and Wikidata names |
| 1485 | none), which answers only for the names it is certain about. |
| 1486 | |
| 1487 | The jobs lane reads that site's careers page instead of guessing a |
| 1488 | domain from the name, and only such a confirmed site can tie a board to |
| 1489 | the company (it links the board, or the board states the name the site |
| 1490 | states). A mock run and a run with the jobs lane excluded ask the |
| 1491 | resolver nothing. |
| 1492 | """ |
| 1493 | sites: dict[str, str] = {} |
| 1494 | lookups = not (mock or "jobs" in env.exclude_sources(config)) |
| 1495 | for company in companies: |
| 1496 | if isinstance(company, str): |
| 1497 | company = {"name": company, "site": ""} |
| 1498 | name, site = company["name"], company.get("site") or "" |
| 1499 | if not site and lookups: |
| 1500 | site = str( |
| 1501 | company_resolve.resolve_company( |
| 1502 | name, listing=False, config=config, |
| 1503 | ).get("company_site") or "" |
| 1504 | ) |
| 1505 | if site: |
| 1506 | sys.stderr.write(f"[Resolve] --company {name}: official site {site}\n") |
| 1507 | if site: |
| 1508 | sites[name] = site |
| 1509 | return sites |
| 1510 | |
| 1511 | |
| 1512 | def _company_for_jobs( |
| 1513 | company: dict, |
| 1514 | host_tickers: list[dict] | None, |
| 1515 | topic: str, |
| 1516 | official_site: str = "", |
| 1517 | host_names: list[str] | None = None, |
| 1518 | host_sites: dict[str, str] | None = None, |
| 1519 | ) -> dict: |
| 1520 | """The company the jobs lane searches for the main topic. |
| 1521 | |
| 1522 | The company Wikidata resolved, as it is; when that company is the topic |
| 1523 | and came with no site, the topic's official site is added as |
| 1524 | ``topic_site``. When Wikidata named none (it |
| 1525 | failed, or the topic is a person it is not certain about): |
| 1526 | |
| 1527 | - the topic's own official site, when the run knows one, is added as |
| 1528 | ``topic_site``, so the lane reads that site's careers page instead of |
| 1529 | guessing a domain from the topic's name; |
| 1530 | - with no official site, the site the host passed for a ``--company`` |
| 1531 | entry that is the topic itself is the ``topic_site``; |
| 1532 | - the companies the host named that are not the topic itself are added |
| 1533 | as ``host_companies``: those of ``--company`` (``host_names``), then |
| 1534 | those of its usable ``--ticker`` pairs, each in the order given and a |
| 1535 | company named both ways once. The jobs lane tries each after the |
| 1536 | topic's own name finds no board, and uses the first one that has a |
| 1537 | board. |
| 1538 | """ |
| 1539 | if company.get("company"): |
| 1540 | if ( |
| 1541 | official_site.strip() and not company.get("company_site") |
| 1542 | and yahoo_finance._same_company_name(topic, str(company["company"])) |
| 1543 | ): |
| 1544 | # A company named with no site (the Yahoo fallback after a |
| 1545 | # failed Wikidata lookup) is the topic itself, so the site the |
| 1546 | # run knows is its site. |
| 1547 | return {**company, "topic_site": official_site.strip()} |
| 1548 | return company |
| 1549 | found = dict(company) |
| 1550 | if official_site.strip(): |
| 1551 | found["topic_site"] = official_site.strip() |
| 1552 | else: |
| 1553 | own = next( |
| 1554 | (site for name, site in (host_sites or {}).items() |
| 1555 | if site and yahoo_finance._same_company_name(topic, name)), |
| 1556 | "", |
| 1557 | ) |
| 1558 | if own: |
| 1559 | found["topic_site"] = own |
| 1560 | names: list[str] = [] |
| 1561 | named = list(host_names or []) + [ |
| 1562 | pair.get("company") or "" for pair in host_tickers or [] if not pair.get("reason") |
| 1563 | ] |
| 1564 | for name in named: |
| 1565 | if not name or yahoo_finance._same_company_name(topic, name): |
| 1566 | continue |
| 1567 | if any(yahoo_finance._same_company_name(earlier, name) for earlier in names): |
| 1568 | continue |
| 1569 | names.append(name) |
| 1570 | if names: |
| 1571 | found["host_companies"] = names |
| 1572 | sites = {name: site for name, site in (host_sites or {}).items() if name in names} |
| 1573 | if sites: |
| 1574 | # The confirmed official site of a company the host named. |
| 1575 | found["host_company_sites"] = sites |
| 1576 | return found if found != dict(company) else company |
| 1577 | |
| 1578 | |
| 1579 | def truncate_comparison_entities(entities: list[str], *, warn: bool = True) -> list[str]: |
| 1580 | """Cap a vs-entity list at COMPARISON_ENTITY_MAX; optionally warn on stderr.""" |
| 1581 | ceiling = competitors_mod.COMPARISON_ENTITY_MAX |
| 1582 | if len(entities) <= ceiling: |
| 1583 | return list(entities) |
| 1584 | kept = entities[:ceiling] |
| 1585 | dropped = entities[ceiling:] |
| 1586 | if warn: |
| 1587 | sys.stderr.write( |
| 1588 | f"[Competitors] vs-topic has {len(entities)} entities; " |
| 1589 | f"using first {ceiling}, dropped: {', '.join(dropped)}\n" |
| 1590 | ) |
| 1591 | return kept |
| 1592 | |
| 1593 | |
| 1594 | def apply_vs_competitor_routing( |
| 1595 | topic: str, |
| 1596 | *, |
| 1597 | competitors_flag: int | None, |
| 1598 | comp_enabled: bool, |
| 1599 | comp_count: int, |
| 1600 | comp_explicit: list[str], |
| 1601 | comp_plan: dict[str, dict] | None = None, |
| 1602 | ) -> tuple[str, bool, int, list[str]]: |
| 1603 | """Apply vs-string / plan routing on top of resolve_competitors_args. |
| 1604 | |
| 1605 | Precedence for *who* runs: |
| 1606 | 1. ``--competitors-list`` (explicit peers; topic unchanged) |
| 1607 | 2. Pure discover-N (``--competitors`` without list or plan) — topic |
| 1608 | unchanged, even if it contains ``vs`` |
| 1609 | 3. vs-string split (first entity becomes main topic) — used for bare |
| 1610 | vs-topics and vs-topic + ``--competitors-plan`` |
| 1611 | 4. ``--competitors-plan`` keys as peers when there is no vs-string |
| 1612 | (including when ``--competitors N`` is also set) |
| 1613 | """ |
| 1614 | from lib import planner as _planner |
| 1615 | |
| 1616 | if comp_explicit: |
| 1617 | return topic, True, len(comp_explicit), list(comp_explicit) |
| 1618 | |
| 1619 | # Preserve discover-N semantics: numeric flag without plan/list must not |
| 1620 | # rewrite a vs-string into named peers. |
| 1621 | if competitors_flag is not None and not comp_plan: |
| 1622 | return topic, True, comp_count, [] |
| 1623 | |
| 1624 | vs_entities = truncate_comparison_entities( |
| 1625 | _planner._comparison_entities(topic, uncapped=True), |
| 1626 | warn=True, |
| 1627 | ) |
| 1628 | if len(vs_entities) >= 2: |
| 1629 | main, peers = vs_entities[0], vs_entities[1:] |
| 1630 | sys.stderr.write( |
| 1631 | f"[Competitors] vs-mode: routing to N-pass fanout: " |
| 1632 | f"{main} vs {' vs '.join(peers)}\n" |
| 1633 | ) |
| 1634 | return main, True, len(peers), peers |
| 1635 | |
| 1636 | if comp_plan: |
| 1637 | plan_peers = [ |
| 1638 | (entry.get("_name") or key) |
| 1639 | for key, entry in comp_plan.items() |
| 1640 | ] |
| 1641 | plan_peers = [name for name in plan_peers if name] |
| 1642 | if len(plan_peers) > COMPETITORS_MAX: |
| 1643 | sys.stderr.write( |
| 1644 | f"[Competitors] --competitors-plan has {len(plan_peers)} entries, " |
| 1645 | f"clamping to {COMPETITORS_MAX}.\n" |
| 1646 | ) |
| 1647 | plan_peers = plan_peers[:COMPETITORS_MAX] |
| 1648 | return topic, True, len(plan_peers), plan_peers |
| 1649 | |
| 1650 | return topic, comp_enabled, comp_count, comp_explicit |
| 1651 | |
| 1652 | |
| 1653 | def resolve_competitors_args(args: argparse.Namespace) -> tuple[bool, int, list[str]]: |
| 1654 | """Normalize competitors flags into (enabled, count, explicit_list). |
| 1655 | |
| 1656 | - (False, 0, []) when neither flag, list, nor plan is set. |
| 1657 | - An explicit ``--competitors-list`` always wins; count is derived from list length. |
| 1658 | - ``--competitors-plan`` alone enables mode with an empty peer list; vs-routing |
| 1659 | fills peers from the vs-string or plan keys. |
| 1660 | - A numeric count outside [1, 6] is clamped with a stderr warning. |
| 1661 | - count <= 0 (explicit) raises SystemExit(2). |
| 1662 | """ |
| 1663 | explicit_list: list[str] = [] |
| 1664 | list_flag_provided = args.competitors_list is not None |
| 1665 | if list_flag_provided: |
| 1666 | explicit_list = [ |
| 1667 | entity.strip() |
| 1668 | for entity in args.competitors_list.split(",") |
| 1669 | if entity.strip() |
| 1670 | ] |
| 1671 | if not explicit_list: |
| 1672 | sys.stderr.write("[Competitors] --competitors-list is empty.\n") |
| 1673 | raise SystemExit(2) |
| 1674 | |
| 1675 | competitors_flag = args.competitors |
| 1676 | list_present = bool(explicit_list) |
| 1677 | flag_present = competitors_flag is not None |
| 1678 | plan_present = bool(getattr(args, "competitors_plan", None)) |
| 1679 | |
| 1680 | if not list_present and not flag_present and not plan_present: |
| 1681 | return False, 0, [] |
| 1682 | |
| 1683 | if list_present: |
| 1684 | count = len(explicit_list) |
| 1685 | if flag_present and competitors_flag != count: |
| 1686 | sys.stderr.write( |
| 1687 | f"[Competitors] --competitors={competitors_flag} ignored; using " |
| 1688 | f"{count} entries from --competitors-list.\n" |
| 1689 | ) |
| 1690 | if count > COMPETITORS_MAX: |
| 1691 | sys.stderr.write( |
| 1692 | f"[Competitors] --competitors-list has {count} entries, clamping to {COMPETITORS_MAX}.\n" |
| 1693 | ) |
| 1694 | explicit_list = explicit_list[:COMPETITORS_MAX] |
| 1695 | count = COMPETITORS_MAX |
| 1696 | return True, count, explicit_list |
| 1697 | |
| 1698 | if flag_present: |
| 1699 | count = competitors_flag |
| 1700 | if count < COMPETITORS_MIN: |
| 1701 | sys.stderr.write( |
| 1702 | f"[Competitors] --competitors must be >= {COMPETITORS_MIN} (got {count}).\n" |
| 1703 | ) |
| 1704 | raise SystemExit(2) |
| 1705 | if count > COMPETITORS_MAX: |
| 1706 | sys.stderr.write( |
| 1707 | f"[Competitors] --competitors={count} exceeds max {COMPETITORS_MAX}; clamping.\n" |
| 1708 | ) |
| 1709 | count = COMPETITORS_MAX |
| 1710 | return True, count, [] |
| 1711 | |
| 1712 | # plan_present alone: enable; peers filled by apply_vs_competitor_routing. |
| 1713 | return True, 0, [] |
| 1714 | |
| 1715 | |
| 1716 | def _missing_sources_for_promo(diag: dict[str, object]) -> str | None: |
| 1717 | available = set(diag.get("available_sources") or []) |
| 1718 | missing = [] |
| 1719 | if "reddit" not in available: |
| 1720 | missing.append("reddit") |
| 1721 | # X is optional. A successful run without X must reach the research output |
| 1722 | # without an authentication or browser-cookie promo in front of it. |
| 1723 | # The web promo nudges toward a paid backend for higher-quality web search. |
| 1724 | # Grounding is now available keyless on non-native hosts, so key the promo on |
| 1725 | # the absence of a *paid* backend, not on grounding availability. Suppress it |
| 1726 | # entirely on native-search hosts, where the model's own search is better and |
| 1727 | # setting a paid engine key would be the wrong advice. |
| 1728 | if not diag.get("native_web_backend") and not diag.get("native_search"): |
| 1729 | missing.append("web") |
| 1730 | if not missing: |
| 1731 | return None |
| 1732 | return missing[0] |
| 1733 | |
| 1734 | |
| 1735 | def _optional_x_omission_text( |
| 1736 | diag: dict[str, object], |
| 1737 | requested_sources: list[str] | None, |
| 1738 | ) -> str | None: |
| 1739 | """Return a non-blocking post-result note for a default run without X. |
| 1740 | |
| 1741 | Explicit ``--search`` runs already define their intended source boundary, |
| 1742 | so they do not need an omission note. Doctor/diagnose remains the place for |
| 1743 | X setup or repair instructions. |
| 1744 | """ |
| 1745 | if requested_sources is not None: |
| 1746 | return None |
| 1747 | available = set(diag.get("available_sources") or []) |
| 1748 | if "x" in available: |
| 1749 | return None |
| 1750 | return ( |
| 1751 | "Optional source omitted: X/Twitter was not enabled; research " |
| 1752 | "continued with the available sources." |
| 1753 | ) |
| 1754 | |
| 1755 | |
| 1756 | def _show_runtime_ui( |
| 1757 | report: schema.Report, |
| 1758 | progress: ui.ProgressDisplay, |
| 1759 | diag: dict[str, object], |
| 1760 | suppress_web_promo: bool = False, |
| 1761 | ) -> None: |
| 1762 | counts = {source: len(items) for source, items in report.items_by_source.items()} |
| 1763 | display_sources = list( |
| 1764 | dict.fromkeys( |
| 1765 | [ |
| 1766 | # Subquery sources, not source_weights: the sanitizer weights |
| 1767 | # every eligible source, so weights alone would print |
| 1768 | # "Digg: 0 clusters" for a source that was never searched. |
| 1769 | *( |
| 1770 | source |
| 1771 | for subquery in report.query_plan.subqueries |
| 1772 | for source in subquery.sources |
| 1773 | ), |
| 1774 | *report.items_by_source.keys(), |
| 1775 | *report.errors_by_source.keys(), |
| 1776 | ] |
| 1777 | ) |
| 1778 | ) |
| 1779 | progress.end_processing() |
| 1780 | progress.show_complete( |
| 1781 | source_counts=counts, |
| 1782 | display_sources=display_sources, |
| 1783 | ) |
| 1784 | promo = _missing_sources_for_promo(diag) |
| 1785 | # The `web` promo nudges users to set BRAVE_API_KEY / SERPER_API_KEY, which |
| 1786 | # is wrong advice when a hosting reasoning model (Claude Code, Codex, |
| 1787 | # Hermes, Gemini) is driving — those already have WebSearch and can |
| 1788 | # pre-resolve Step 0.55 themselves. Suppress the web promo when a hosting |
| 1789 | # model signal is present (--plan or --competitors-plan was passed). |
| 1790 | if promo: |
| 1791 | if suppress_web_promo and promo == "web": |
| 1792 | return |
| 1793 | if suppress_web_promo and promo == "both": |
| 1794 | # "both" means reddit + web both missing; still nudge reddit but |
| 1795 | # skip the web line. show_promo has a per-source variant. |
| 1796 | progress.show_promo("reddit", diag=diag) |
| 1797 | return |
| 1798 | progress.show_promo(promo, diag=diag) |
| 1799 | |
| 1800 | |
| 1801 | REPORT_CACHE_VERSION = "last30days-report-cache/v2" |
| 1802 | DEFAULT_REPORT_CACHE_TTL_SECONDS = 3600 |
| 1803 | |
| 1804 | |
| 1805 | class _CachedReport(NamedTuple): |
| 1806 | report: schema.Report |
| 1807 | entity_reports: list[tuple[str, schema.Report]] | None |
| 1808 | path: Path |
| 1809 | fingerprint: bytes |
| 1810 | x_envelope_sha256: str | None |
| 1811 | |
| 1812 | |
| 1813 | def _last_report_cache_path() -> Path | None: |
| 1814 | if env.CONFIG_DIR is None: |
| 1815 | return None |
| 1816 | return env.CONFIG_DIR / "last-report.json" |
| 1817 | |
| 1818 | |
| 1819 | @contextmanager |
| 1820 | def _report_cache_lock(cache_path: Path) -> Iterator[None]: |
| 1821 | # The lock file stays in place so replacing the report cannot split writers across different inodes. |
| 1822 | fd = os.open(cache_path.with_suffix(".lock"), os.O_CREAT | os.O_RDWR, 0o600) |
| 1823 | try: |
| 1824 | if os.name == "nt": |
| 1825 | import msvcrt |
| 1826 | |
| 1827 | msvcrt.locking(fd, msvcrt.LK_LOCK, 1) |
| 1828 | try: |
| 1829 | yield |
| 1830 | finally: |
| 1831 | msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) |
| 1832 | else: |
| 1833 | import fcntl |
| 1834 | |
| 1835 | fcntl.flock(fd, fcntl.LOCK_EX) |
| 1836 | yield |
| 1837 | finally: |
| 1838 | os.close(fd) |
| 1839 | |
| 1840 | |
| 1841 | def _report_cache_ttl_seconds(config: dict[str, object]) -> int: |
| 1842 | raw = os.environ.get("LAST30DAYS_REPORT_CACHE_TTL_SECONDS") |
| 1843 | if raw is None: |
| 1844 | raw = config.get("LAST30DAYS_REPORT_CACHE_TTL_SECONDS") |
| 1845 | if raw is None or raw == "": |
| 1846 | return DEFAULT_REPORT_CACHE_TTL_SECONDS |
| 1847 | try: |
| 1848 | return max(0, int(raw)) |
| 1849 | except (TypeError, ValueError): |
| 1850 | return DEFAULT_REPORT_CACHE_TTL_SECONDS |
| 1851 | |
| 1852 | |
| 1853 | def _is_report_cache_fresh(timestamp: object, ttl_seconds: int) -> bool: |
| 1854 | return env.is_timestamp_fresh(timestamp, ttl_seconds) |
| 1855 | |
| 1856 | |
| 1857 | def _write_last_run( |
| 1858 | topic: str, |
| 1859 | report: "schema.Report", |
| 1860 | entity_reports: list[tuple[str, schema.Report]] | None = None, |
| 1861 | *, |
| 1862 | x_envelope_sha256: str | None = None, |
| 1863 | research_options: dict[str, object] | None = None, |
| 1864 | expected_cache_fingerprint: bytes | None = None, |
| 1865 | ) -> bool: |
| 1866 | # The stored digest binds research replay to the host evidence it used. |
| 1867 | try: |
| 1868 | if env.CONFIG_DIR is None: |
| 1869 | return False |
| 1870 | target = env.CONFIG_DIR |
| 1871 | cached_reports = entity_reports or [(report.topic, report)] |
| 1872 | has_private_corpus = any( |
| 1873 | cached_report.items_by_source.get("corpus") |
| 1874 | for _, cached_report in cached_reports |
| 1875 | ) |
| 1876 | _ensure_output_directory(target, private=has_private_corpus) |
| 1877 | counts = {source: len(items) for source, items in report.items_by_source.items()} |
| 1878 | payload = { |
| 1879 | "topic": topic, |
| 1880 | "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(), |
| 1881 | "sources": counts, |
| 1882 | "total": sum(counts.values()), |
| 1883 | "report_cache": str(target / "last-report.json"), |
| 1884 | "comparison": bool(entity_reports), |
| 1885 | } |
| 1886 | run_id = uuid.uuid4().hex |
| 1887 | cache_payload = { |
| 1888 | "schema": REPORT_CACHE_VERSION, |
| 1889 | "run_id": run_id, |
| 1890 | "topic": topic, |
| 1891 | "timestamp": payload["timestamp"], |
| 1892 | "comparison": bool(entity_reports), |
| 1893 | "x_envelope_sha256": x_envelope_sha256 or None, |
| 1894 | "research_options": ( |
| 1895 | research_options if research_options is not None |
| 1896 | else _cache_research_options(build_parser().parse_args([])) |
| 1897 | ), |
| 1898 | "reports": [ |
| 1899 | {"entity": label, "report": schema.to_dict(cached_report)} |
| 1900 | for label, cached_report in cached_reports |
| 1901 | ], |
| 1902 | } |
| 1903 | report_cache_path = target / "last-report.json" |
| 1904 | report_json = json.dumps(cache_payload, indent=2) |
| 1905 | run_json = json.dumps(payload, indent=2) |
| 1906 | with _report_cache_lock(report_cache_path): |
| 1907 | if ( |
| 1908 | expected_cache_fingerprint is not None |
| 1909 | and hashlib.sha256(report_cache_path.read_bytes()).digest() |
| 1910 | != expected_cache_fingerprint |
| 1911 | ): |
| 1912 | return False |
| 1913 | replace_private_text(report_cache_path, report_json) |
| 1914 | replace_private_text(target / "last-run.json", run_json) |
| 1915 | sys.stderr.write(f"[last30days] Follow-up cache ID: {run_id}\n") |
| 1916 | return True |
| 1917 | except Exception as exc: |
| 1918 | # Never fatal, but never silent either (#787's lesson): callers that |
| 1919 | # promise cache state (drill chaining) branch on the return value. |
| 1920 | sys.stderr.write(f"[last30days] warning: could not write run cache: {exc}\n") |
| 1921 | return False |
| 1922 | |
| 1923 | |
| 1924 | def _load_last_report_cache( |
| 1925 | topic: str | None, |
| 1926 | ttl_seconds: int = DEFAULT_REPORT_CACHE_TTL_SECONDS, |
| 1927 | *, |
| 1928 | x_envelope_sha256: str | None = None, |
| 1929 | research_options: dict[str, object] | None = None, |
| 1930 | requested_window: tuple[str, str] | None = None, |
| 1931 | use_cached_envelopes: bool = False, |
| 1932 | run_id: str | None = None, |
| 1933 | ) -> _CachedReport | None: |
| 1934 | cache_path = _last_report_cache_path() |
| 1935 | if cache_path is None or not cache_path.exists(): |
| 1936 | return None |
| 1937 | try: |
| 1938 | raw = cache_path.read_bytes() |
| 1939 | payload = json.loads(raw.decode("utf-8")) |
| 1940 | if not isinstance(payload, dict): |
| 1941 | raise TypeError("report cache payload must be a JSON object") |
| 1942 | if payload.get("schema") != REPORT_CACHE_VERSION: |
| 1943 | return None |
| 1944 | if not _is_report_cache_fresh(payload.get("timestamp"), ttl_seconds): |
| 1945 | return None |
| 1946 | if run_id is not None and payload.get("run_id") != run_id: |
| 1947 | return None |
| 1948 | # Explicit follow-ups consume the saved snapshot without needing its |
| 1949 | # original envelope files. Research replay still matches their digest. |
| 1950 | cached_digest = payload.get("x_envelope_sha256") or None |
| 1951 | if cached_digest is not None and not isinstance(cached_digest, str): |
| 1952 | return None |
| 1953 | if (not use_cached_envelopes or x_envelope_sha256 is not None) and cached_digest != x_envelope_sha256: |
| 1954 | return None |
| 1955 | cached_options = payload.get("research_options") or {} |
| 1956 | if not isinstance(cached_options, dict): |
| 1957 | return None |
| 1958 | if any(cached_options.get(key) != value for key, value in (research_options or {}).items()): |
| 1959 | return None |
| 1960 | cached_topic = str(payload.get("topic") or "").strip().lower() |
| 1961 | if topic is not None and cached_topic != topic.strip().lower(): |
| 1962 | return None |
| 1963 | reports_payload = payload.get("reports") or [] |
| 1964 | if not reports_payload: |
| 1965 | return None |
| 1966 | entity_reports = [ |
| 1967 | (str(item.get("entity") or ""), schema.report_from_dict(item["report"])) |
| 1968 | for item in reports_payload |
| 1969 | if isinstance(item, dict) and isinstance(item.get("report"), dict) |
| 1970 | ] |
| 1971 | if not entity_reports: |
| 1972 | return None |
| 1973 | if requested_window is not None and any( |
| 1974 | (report.range_from, report.range_to) != requested_window |
| 1975 | for _, report in entity_reports |
| 1976 | ): |
| 1977 | return None |
| 1978 | comparison = payload.get("comparison") |
| 1979 | if comparison and (len(entity_reports) < 2 or len(entity_reports) != len(reports_payload)): |
| 1980 | return None |
| 1981 | return _CachedReport( |
| 1982 | entity_reports[0][1], entity_reports if comparison else None, |
| 1983 | cache_path, hashlib.sha256(raw).digest(), cached_digest, |
| 1984 | ) |
| 1985 | except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as exc: |
| 1986 | sys.stderr.write( |
| 1987 | f"[last30days] Could not read report cache {cache_path}: " |
| 1988 | f"{type(exc).__name__}: {exc}\n" |
| 1989 | ) |
| 1990 | return None |
| 1991 | |
| 1992 | |
| 1993 | def _cache_research_options( |
| 1994 | args: argparse.Namespace, config: dict[str, object] | None = None, *, supplied_only: bool = False, |
| 1995 | resolved_corpus_dirs: list[Path] | None = None, |
| 1996 | external_plan: dict | None = None, |
| 1997 | ) -> dict[str, object]: |
| 1998 | names = ( |
| 1999 | "search", "quick", "deep", "mock", "web_backend", "perplexity_search_type", |
| 2000 | "hiring_signals", "x_handle", "x_related", "official_site", "no_x_handle", |
| 2001 | "subreddits", "dedicated_subreddits", "devto_tags", "tiktok_hashtags", |
| 2002 | "tiktok_creators", "ig_creators", "max_results", "max_per_source", |
| 2003 | "max_source_fetches", "auto_resolve", "github_user", "github_repo", "ticker", |
| 2004 | "company", "jobs_board", |
| 2005 | "trustpilot_domain", "amazon_query", "meta_ads_page", "telegram_sources", |
| 2006 | "competitors", "competitors_list", "polymarket_keywords", "corpus_all_time", "drill", |
| 2007 | "employer", "linkedin", |
| 2008 | ) |
| 2009 | options = { |
| 2010 | name: getattr(args, name, None) for name in names |
| 2011 | if not supplied_only or name in getattr(args, "_explicit_options", ()) |
| 2012 | } |
| 2013 | if not supplied_only or "email" in getattr(args, "_explicit_options", ()): |
| 2014 | # The person anchor counts toward the cache match, but the address is |
| 2015 | # stored only as a hash. |
| 2016 | email = (getattr(args, "email", None) or "").strip().lower() |
| 2017 | options["email_sha256"] = hashlib.sha256(email.encode("utf-8")).hexdigest() if email else None |
| 2018 | if not supplied_only or "corpus" in getattr(args, "_explicit_options", ()): |
| 2019 | if resolved_corpus_dirs is None: |
| 2020 | resolved_corpus_dirs = corpus.resolve_directories( |
| 2021 | args.corpus, (config or {}).get("LAST30DAYS_CORPUS_DIRS") |
| 2022 | ) |
| 2023 | if "corpus" in { |
| 2024 | value.strip().lower() |
| 2025 | for value in str((config or {}).get("EXCLUDE_SOURCES") or "").split(",") |
| 2026 | }: |
| 2027 | resolved_corpus_dirs = [] |
| 2028 | options["corpus_sha256"] = hashlib.sha256(json.dumps([ |
| 2029 | os.path.normcase(str(path)) for path in resolved_corpus_dirs |
| 2030 | ]).encode("utf-8")).hexdigest() |
| 2031 | for name in ("plan", "competitors_plan"): |
| 2032 | raw = getattr(args, name, None) |
| 2033 | if not supplied_only: |
| 2034 | options[name] = None |
| 2035 | if raw: |
| 2036 | try: |
| 2037 | if name == "plan" and external_plan is not None: |
| 2038 | content = json.dumps(external_plan, sort_keys=True) |
| 2039 | else: |
| 2040 | content = Path(raw).read_text(encoding="utf-8") if os.path.isfile(raw) else raw |
| 2041 | content = json.dumps(json.loads(content), sort_keys=True) |
| 2042 | except (OSError, ValueError): |
| 2043 | content = raw |
| 2044 | options[name] = hashlib.sha256(content.encode("utf-8")).hexdigest() |
| 2045 | if not supplied_only: |
| 2046 | rendering_keys = { |
| 2047 | "FUN_LEVEL", "ELI5_MODE", "LAST30DAYS_REGISTER", "LAST30DAYS_MEMORY_DIR", |
| 2048 | "LAST30DAYS_REPORT_CACHE_TTL_SECONDS", "LAST30DAYS_STORE", "LAST30DAYS_DEBUG", |
| 2049 | "LAST30DAYS_STRICT_EXIT", "LAST30DAYS_VERIFY_FRESHNESS", "LAST30DAYS_PUBLISH_PASSWORD", |
| 2050 | "LAST30DAYS_CORPUS_DIRS", |
| 2051 | } |
| 2052 | research_keys = { |
| 2053 | "INCLUDE_SOURCES", "EXCLUDE_SOURCES", "TELEGRAM_SOURCES", "BSKY_HANDLE", |
| 2054 | "BSKY_SEARCH_HOST", "FROM_BROWSER", "BROWSER_CONSENT", "BROWSER_CDP_URL", |
| 2055 | "DEGRADED_TRANSCRIPT_THRESHOLD", |
| 2056 | } |
| 2057 | relevant_config = {} |
| 2058 | for key, value in (config or {}).items(): |
| 2059 | if key.startswith("_") or key in rendering_keys: |
| 2060 | continue |
| 2061 | if key.endswith(("_KEY", "_TOKEN", "_PASSWORD", "_SECRET", "_COOKIE")) or key == "CT0": |
| 2062 | if value: |
| 2063 | relevant_config[key] = True |
| 2064 | elif key in research_keys or key.startswith("LAST30DAYS_") or key.endswith(("_BASE_URL", "_MODEL_PIN")): |
| 2065 | relevant_config[key] = value |
| 2066 | if env.x_api_opt_in(): |
| 2067 | relevant_config[env.X_API_OPT_IN_VAR] = True |
| 2068 | options["config_sha256"] = hashlib.sha256( |
| 2069 | json.dumps(relevant_config, sort_keys=True, default=str).encode("utf-8") |
| 2070 | ).hexdigest() |
| 2071 | return options |
| 2072 | |
| 2073 | |
| 2074 | def _config_truthy(value: object) -> bool: |
| 2075 | return str(value or "").strip().lower() in {"1", "true", "yes", "on"} |
| 2076 | |
| 2077 | |
| 2078 | def _freshness_enabled(args: argparse.Namespace, config: dict[str, object]) -> bool: |
| 2079 | if args.verify_freshness is not None: |
| 2080 | return bool(args.verify_freshness) |
| 2081 | return _config_truthy(config.get("LAST30DAYS_VERIFY_FRESHNESS")) |
| 2082 | |
| 2083 | |
| 2084 | def _update_cached_freshness(cached: _CachedReport) -> bool: |
| 2085 | """Rewrite cached report bodies without extending the research-cache TTL.""" |
| 2086 | try: |
| 2087 | with _report_cache_lock(cached.path): |
| 2088 | raw = cached.path.read_bytes() |
| 2089 | if hashlib.sha256(raw).digest() != cached.fingerprint: |
| 2090 | return False |
| 2091 | payload = json.loads(raw.decode("utf-8")) |
| 2092 | existing = payload.get("reports") or [] |
| 2093 | if cached.entity_reports: |
| 2094 | cached_reports = cached.entity_reports |
| 2095 | else: |
| 2096 | label = ( |
| 2097 | str(existing[0].get("entity") or cached.report.topic) |
| 2098 | if existing and isinstance(existing[0], dict) |
| 2099 | else cached.report.topic |
| 2100 | ) |
| 2101 | cached_reports = [(label, cached.report)] |
| 2102 | payload["reports"] = [ |
| 2103 | {"entity": label, "report": schema.to_dict(report)} |
| 2104 | for label, report in cached_reports |
| 2105 | ] |
| 2106 | replace_private_text(cached.path, json.dumps(payload, indent=2)) |
| 2107 | return True |
| 2108 | except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc: |
| 2109 | sys.stderr.write( |
| 2110 | f"[last30days] warning: could not update freshness cache: {exc}\n" |
| 2111 | ) |
| 2112 | return False |
| 2113 | |
| 2114 | |
| 2115 | def _verify_report_set( |
| 2116 | report: schema.Report, |
| 2117 | entity_reports: list[tuple[str, schema.Report]] | None, |
| 2118 | *, |
| 2119 | allow_network: bool, |
| 2120 | ) -> None: |
| 2121 | reports = [item for _, item in entity_reports] if entity_reports else [report] |
| 2122 | for current_report in reports: |
| 2123 | freshness.verify_report(current_report, allow_network=allow_network) |
| 2124 | if not any(current_report.freshness_verdicts for current_report in reports): |
| 2125 | # An empty verdict list is a legitimate outcome, but a silent one has |
| 2126 | # already misled operators once; say why there is nothing to show. |
| 2127 | sys.stderr.write( |
| 2128 | "[last30days] Freshness verification found no re-checkable claims" |
| 2129 | " in this report; the verdict list is empty.\n" |
| 2130 | ) |
| 2131 | |
| 2132 | |
| 2133 | def _load_followup_report( |
| 2134 | args: argparse.Namespace, |
| 2135 | config: dict[str, object], |
| 2136 | ) -> _CachedReport | None: |
| 2137 | cached = _load_last_report_cache( |
| 2138 | args.followup_topic, |
| 2139 | ttl_seconds=_report_cache_ttl_seconds(config), |
| 2140 | use_cached_envelopes=True, |
| 2141 | run_id=args.followup_run, |
| 2142 | ) |
| 2143 | if cached is None: |
| 2144 | scope = "" |
| 2145 | if args.followup_run: |
| 2146 | scope = " for the requested run" |
| 2147 | elif args.followup_topic: |
| 2148 | scope = " for the requested topic" |
| 2149 | sys.stderr.write(f"[last30days] No fresh cached report{scope}; run a research pass first.\n") |
| 2150 | return cached |
| 2151 | |
| 2152 | |
| 2153 | def _validate_publish_html(args: argparse.Namespace) -> int | None: |
| 2154 | if args.publish_html and args.emit != "html": |
| 2155 | sys.stderr.write("[last30days] --publish-html requires --emit=html\n") |
| 2156 | return 2 |
| 2157 | return None |
| 2158 | |
| 2159 | |
| 2160 | def _validate_comparison_emit(args: argparse.Namespace, *, is_comparison: bool) -> int | None: |
| 2161 | if is_comparison and args.emit == "brief": |
| 2162 | sys.stderr.write( |
| 2163 | "[last30days] --emit=brief is not supported for comparison or competitor runs; " |
| 2164 | "use --emit=compact, md, context, json, or html.\n" |
| 2165 | ) |
| 2166 | return 2 |
| 2167 | return None |
| 2168 | |
| 2169 | |
| 2170 | def _resolve_synthesis_md(args: argparse.Namespace) -> str | None: |
| 2171 | if not args.synthesis_file: |
| 2172 | return None |
| 2173 | if args.emit == "html": |
| 2174 | return read_synthesis_file(args.synthesis_file) |
| 2175 | sys.stderr.write( |
| 2176 | "[last30days] Warning: --synthesis-file is only used with --emit=html; ignoring.\n" |
| 2177 | ) |
| 2178 | return None |
| 2179 | |
| 2180 | |
| 2181 | def _run_cached_freshness( |
| 2182 | args: argparse.Namespace, |
| 2183 | config: dict[str, object], |
| 2184 | ) -> int: |
| 2185 | publish_exit = _validate_publish_html(args) |
| 2186 | if publish_exit is not None: |
| 2187 | return publish_exit |
| 2188 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 2189 | if save_dir_exit is not None: |
| 2190 | return save_dir_exit |
| 2191 | synthesis_md = _resolve_synthesis_md(args) |
| 2192 | cached = _load_followup_report(args, config) |
| 2193 | if cached is None: |
| 2194 | return 2 |
| 2195 | report, entity_reports, cache_path = cached.report, cached.entity_reports, cached.path |
| 2196 | comp_emit_exit = _validate_comparison_emit(args, is_comparison=bool(entity_reports)) |
| 2197 | if comp_emit_exit is not None: |
| 2198 | return comp_emit_exit |
| 2199 | _verify_report_set(report, entity_reports, allow_network=not args.mock) |
| 2200 | if _update_cached_freshness(cached): |
| 2201 | sys.stderr.write(f"[last30days] Updated freshness verdicts in {cache_path}\n") |
| 2202 | else: |
| 2203 | sys.stderr.write("[last30days] warning: freshness cache update failed\n") |
| 2204 | return _render_save_and_print(args, report, entity_reports, synthesis_md, config) |
| 2205 | |
| 2206 | |
| 2207 | def _drill_config(config: dict[str, object], sources: list[str]) -> dict[str, object]: |
| 2208 | """Enable configured comment enrichments for a deep follow-up.""" |
| 2209 | drill_config = dict(config) |
| 2210 | include = { |
| 2211 | value.strip().lower() |
| 2212 | for value in str(config.get("INCLUDE_SOURCES") or "").split(",") |
| 2213 | if value.strip() |
| 2214 | } |
| 2215 | comment_flags = { |
| 2216 | "youtube": "youtube_comments", |
| 2217 | "tiktok": "tiktok_comments", |
| 2218 | "instagram": "instagram_comments", |
| 2219 | } |
| 2220 | include.update(comment_flags[source] for source in sources if source in comment_flags) |
| 2221 | if include: |
| 2222 | drill_config["INCLUDE_SOURCES"] = ",".join(sorted(include)) |
| 2223 | drill_config["_drill_mode"] = True |
| 2224 | return drill_config |
| 2225 | |
| 2226 | |
| 2227 | def _run_drill( |
| 2228 | args: argparse.Namespace, |
| 2229 | config: dict[str, object], |
| 2230 | ) -> int: |
| 2231 | from lib import planner |
| 2232 | |
| 2233 | cached = _load_followup_report(args, config) |
| 2234 | if cached is None: |
| 2235 | return 2 |
| 2236 | report = cached.report |
| 2237 | if cached.entity_reports: |
| 2238 | sys.stderr.write( |
| 2239 | "[last30days] Drill mode needs a single-topic cached report; " |
| 2240 | "run a research pass for one entity first.\n" |
| 2241 | ) |
| 2242 | return 2 |
| 2243 | |
| 2244 | lookback_days = args.lookback_days |
| 2245 | if lookback_days is None: |
| 2246 | range_from = datetime.date.fromisoformat(report.range_from) |
| 2247 | range_to = datetime.date.fromisoformat(report.range_to) |
| 2248 | lookback_days = (range_to - range_from).days |
| 2249 | as_of_date = args.as_of_date or report.range_to |
| 2250 | |
| 2251 | try: |
| 2252 | matched_clusters = planner.resolve_drill_clusters(report, args.drill) |
| 2253 | drill_plan = planner.build_drill_plan( |
| 2254 | report, |
| 2255 | args.drill, |
| 2256 | clusters=matched_clusters, |
| 2257 | ) |
| 2258 | except planner.DrillTargetError as exc: |
| 2259 | sys.stderr.write(f"[last30days] {exc}\n") |
| 2260 | return 2 |
| 2261 | |
| 2262 | sources = list(drill_plan.source_weights) |
| 2263 | local_only = sources == ["corpus"] |
| 2264 | drill_config = _drill_config(config, sources) |
| 2265 | diag = pipeline.diagnose(drill_config, sources, safe=args.mock or local_only) |
| 2266 | progress = ui.ProgressDisplay( |
| 2267 | f"{report.topic} — drill: {args.drill}", |
| 2268 | show_banner=True, |
| 2269 | ) |
| 2270 | progress.start_processing() |
| 2271 | resolved = report.artifacts.get("resolved") or {} |
| 2272 | try: |
| 2273 | drill_report = pipeline.run( |
| 2274 | # Keep source gating anchored to the cached entity (for example, |
| 2275 | # StockTwits needs the original cashtag/finance context). The |
| 2276 | # external drill plan below remains cluster-focused. |
| 2277 | topic=report.topic, |
| 2278 | config=drill_config, |
| 2279 | depth="deep", |
| 2280 | requested_sources=sources, |
| 2281 | mock=args.mock, |
| 2282 | x_handle=( |
| 2283 | (args.x_handle or resolved.get("x_handle") or None) |
| 2284 | if "x" in sources else None |
| 2285 | ), |
| 2286 | x_related=( |
| 2287 | [value.strip() for value in args.x_related.split(",") if value.strip()] |
| 2288 | if (args.x_related and "x" in sources) else None |
| 2289 | ), |
| 2290 | web_backend=args.web_backend, |
| 2291 | external_plan=schema.to_dict(drill_plan), |
| 2292 | subreddits=( |
| 2293 | ([value.strip().removeprefix("r/") for value in args.subreddits.split(",") if value.strip()] |
| 2294 | if args.subreddits else list(resolved.get("subreddits") or []) or None) |
| 2295 | if "reddit" in sources else None |
| 2296 | ), |
| 2297 | tiktok_hashtags=( |
| 2298 | [value.strip().lstrip("#") for value in args.tiktok_hashtags.split(",") if value.strip()] |
| 2299 | if args.tiktok_hashtags else None |
| 2300 | ), |
| 2301 | tiktok_creators=( |
| 2302 | [value.strip().lstrip("@") for value in args.tiktok_creators.split(",") if value.strip()] |
| 2303 | if args.tiktok_creators else None |
| 2304 | ), |
| 2305 | ig_creators=( |
| 2306 | [value.strip().lstrip("@") for value in args.ig_creators.split(",") if value.strip()] |
| 2307 | if args.ig_creators else None |
| 2308 | ), |
| 2309 | lookback_days=lookback_days, |
| 2310 | as_of_date=as_of_date, |
| 2311 | github_user=( |
| 2312 | (args.github_user or resolved.get("github_user") or None) |
| 2313 | if "github" in sources else None |
| 2314 | ), |
| 2315 | github_repos=( |
| 2316 | ([value.strip() for value in args.github_repo.split(",") if value.strip()] |
| 2317 | if args.github_repo else list(resolved.get("github_repos") or []) or None) |
| 2318 | if "github" in sources else None |
| 2319 | ), |
| 2320 | trustpilot_domain=( |
| 2321 | (args.trustpilot_domain or resolved.get("trustpilot_domain") or None) |
| 2322 | if "trustpilot" in sources else None |
| 2323 | ), |
| 2324 | internal_subrun=True, |
| 2325 | corpus_dirs=args.corpus, |
| 2326 | corpus_all_time=args.corpus_all_time, |
| 2327 | ) |
| 2328 | except Exception: |
| 2329 | progress.end_processing() |
| 2330 | raise |
| 2331 | |
| 2332 | _show_runtime_ui(drill_report, progress, diag, suppress_web_promo=True) |
| 2333 | merged = pipeline.merge_drill_report( |
| 2334 | report, |
| 2335 | drill_report, |
| 2336 | matched_clusters, |
| 2337 | target=args.drill, |
| 2338 | ) |
| 2339 | if _freshness_enabled(args, config): |
| 2340 | _verify_report_set(merged, None, allow_network=not args.mock and not local_only) |
| 2341 | else: |
| 2342 | merged.freshness_verdicts = [] |
| 2343 | is_bound = args.followup_topic is not None or args.followup_run is not None |
| 2344 | if _write_last_run( |
| 2345 | report.topic, merged, |
| 2346 | x_envelope_sha256=cached.x_envelope_sha256, |
| 2347 | research_options=_cache_research_options(args, config), |
| 2348 | expected_cache_fingerprint=cached.fingerprint if is_bound else None, |
| 2349 | ): |
| 2350 | sys.stderr.write(f"[last30days] Updated drill cache in {cached.path}\n") |
| 2351 | else: |
| 2352 | sys.stderr.write("[last30days] warning: drill cache update failed\n") |
| 2353 | |
| 2354 | store_default = str( |
| 2355 | os.environ.get("LAST30DAYS_STORE") |
| 2356 | or config.get("LAST30DAYS_STORE") |
| 2357 | or "" |
| 2358 | ).lower() |
| 2359 | if args.store or store_default in {"1", "true", "yes"}: |
| 2360 | counts = persist_report(merged, store_db=_scoped_store_db(args)) |
| 2361 | sys.stderr.write( |
| 2362 | f"[last30days] Stored {counts['new']} new, " |
| 2363 | f"{counts['updated']} updated findings\n" |
| 2364 | ) |
| 2365 | |
| 2366 | synthesis_md = _resolve_synthesis_md(args) |
| 2367 | return _render_save_and_print(args, merged, None, synthesis_md, config) |
| 2368 | |
| 2369 | |
| 2370 | def _save_discovery_output( |
| 2371 | rendered: str, |
| 2372 | *, |
| 2373 | domain: str, |
| 2374 | emit: str, |
| 2375 | save_dir: str, |
| 2376 | suffix: str = "", |
| 2377 | ) -> Path: |
| 2378 | directory = Path(save_dir).expanduser().resolve() |
| 2379 | directory.mkdir(parents=True, exist_ok=True) |
| 2380 | extension = "json" if emit == "json" else "md" |
| 2381 | safe_suffix = sanitize_suffix(suffix) |
| 2382 | suffix_part = f"-{safe_suffix}" if safe_suffix else "" |
| 2383 | stem = f"{slugify(domain)}-discover-raw{suffix_part}" |
| 2384 | date_str = datetime.datetime.now().strftime("%Y-%m-%d") |
| 2385 | candidates = [directory / f"{stem}.{extension}", directory / f"{stem}-{date_str}.{extension}"] |
| 2386 | candidates.extend(directory / f"{stem}-{date_str}-{index}.{extension}" for index in range(1, 100)) |
| 2387 | encoded = rendered.encode("utf-8") |
| 2388 | for candidate in candidates: |
| 2389 | try: |
| 2390 | fd = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) |
| 2391 | except FileExistsError: |
| 2392 | continue |
| 2393 | with os.fdopen(fd, "wb") as output: |
| 2394 | output.write(encoded) |
| 2395 | return candidate |
| 2396 | raise RuntimeError("Could not find a unique discovery output filename") |
| 2397 | |
| 2398 | |
| 2399 | def _pre_run_prior_state( |
| 2400 | prior: dict[str, object] | None, run_ref: str |
| 2401 | ) -> dict[str, object] | None: |
| 2402 | """Reconstruct the queue state a topic had BEFORE this run identity |
| 2403 | recorded it. |
| 2404 | |
| 2405 | A row whose last_run_ref equals THIS run's run_ref was stamped by this |
| 2406 | very run's own earlier attempt (a finalize retry), so its surface_count |
| 2407 | already includes this run's surfacing: subtract it and keep the prior's |
| 2408 | covered state (covered_at intact) so the retry renders exactly like the |
| 2409 | first attempt did. Only when nothing remains after the subtraction AND |
| 2410 | the row was never covered is the topic genuinely first-ever (no prior). |
| 2411 | """ |
| 2412 | if not prior or prior.get("last_run_ref") != run_ref: |
| 2413 | return prior |
| 2414 | previously = max(0, int(prior["surface_count"]) - 1) |
| 2415 | if previously == 0 and prior["status"] != "covered": |
| 2416 | return None |
| 2417 | adjusted = dict(prior) |
| 2418 | adjusted["surface_count"] = previously |
| 2419 | return adjusted |
| 2420 | |
| 2421 | |
| 2422 | def _annotate_and_record_discovery_queue( |
| 2423 | report: schema.DiscoveryReport, |
| 2424 | args: argparse.Namespace, |
| 2425 | config: dict[str, object], |
| 2426 | run_ref: str | None = None, |
| 2427 | ) -> schema.DiscoveryReport: |
| 2428 | """Stamp queue annotations onto report topics, then record this surfacing. |
| 2429 | |
| 2430 | Order matters: annotations describe the queue state BEFORE this run, so |
| 2431 | each topic is matched first and recorded second. The queue is on by |
| 2432 | default; the resolved config value LAST30DAYS_DISCOVERY_QUEUE == "off" |
| 2433 | (env var or .env, via env.get_config) disables it. Scoped runs |
| 2434 | (--save-dir) write the scoped research.db, never the global one. Runs |
| 2435 | synchronously after the pipeline returns - this writes disk, so the |
| 2436 | abandon-on-timeout daemon-thread pattern is forbidden here. |
| 2437 | |
| 2438 | ``run_ref`` overrides the run identity: the finalize leg passes the |
| 2439 | pending report's leg-2 run_ref through so a finalize retry records (and |
| 2440 | annotates) as the SAME run - store.record_discovery_surfacing skips the |
| 2441 | double-count, and rows this very run identity stamped are not "prior" |
| 2442 | state, so retries render identically instead of claiming a resurfacing. |
| 2443 | """ |
| 2444 | queue_setting = str(config.get("LAST30DAYS_DISCOVERY_QUEUE") or "").strip().lower() |
| 2445 | if queue_setting == "off" or not report.topics: |
| 2446 | return report |
| 2447 | |
| 2448 | import dataclasses |
| 2449 | |
| 2450 | import store |
| 2451 | |
| 2452 | run_ref = run_ref or f"discover:{report.domain or 'trending'}:{report.generated_at}" |
| 2453 | as_of = (report.generated_at or "")[:10] or report.range_to |
| 2454 | annotated: list[schema.DiscoveryTopic] = [] |
| 2455 | with store.scoped_db(_scoped_store_db(args)): |
| 2456 | store.init_db() |
| 2457 | # Phase 1: match EVERY topic before recording ANY. Interleaving |
| 2458 | # match+record in one loop lets topic N fuzzy-match a same-anchor |
| 2459 | # sibling row this very run recorded seconds earlier, falsely |
| 2460 | # annotating a first-ever topic as "surfaced 2nd time". |
| 2461 | # A row stamped by THIS run identity is this run's own earlier |
| 2462 | # attempt (finalize retry), not prior state: reconstruct the pre-run |
| 2463 | # state (count minus this run's own surfacing, covered state kept) |
| 2464 | # so retries render identically for topics WITH history too. |
| 2465 | priors = [ |
| 2466 | _pre_run_prior_state(prior, run_ref) |
| 2467 | for prior in ( |
| 2468 | store.match_discovery_topic(topic.name) for topic in report.topics |
| 2469 | ) |
| 2470 | ] |
| 2471 | # Phase 2: record this run's surfacings. A topic whose (possibly |
| 2472 | # fuzzy) prior row is covered inherits that covered state, so a |
| 2473 | # user's covered mark survives judge naming drift instead of |
| 2474 | # silently forking into a fresh uncovered row. |
| 2475 | for topic, prior in zip(report.topics, priors): |
| 2476 | inherit_covered_at = None |
| 2477 | if prior and prior["status"] == "covered": |
| 2478 | inherit_covered_at = prior["covered_at"] or prior["last_surfaced"] |
| 2479 | store.record_discovery_surfacing( |
| 2480 | topic.name, |
| 2481 | domain=report.domain, |
| 2482 | run_ref=run_ref, |
| 2483 | as_of=as_of, |
| 2484 | inherit_covered_at=inherit_covered_at, |
| 2485 | ) |
| 2486 | for topic, prior in zip(report.topics, priors): |
| 2487 | if prior: |
| 2488 | topic = dataclasses.replace( |
| 2489 | topic, |
| 2490 | previously_surfaced_count=prior["surface_count"], |
| 2491 | last_surfaced=prior["last_surfaced"], |
| 2492 | covered=prior["status"] == "covered", |
| 2493 | ) |
| 2494 | annotated.append(topic) |
| 2495 | return dataclasses.replace(report, topics=annotated) |
| 2496 | |
| 2497 | |
| 2498 | def _record_discovery_queue_safely( |
| 2499 | report: schema.DiscoveryReport, |
| 2500 | args: argparse.Namespace, |
| 2501 | config: dict[str, object], |
| 2502 | run_ref: str | None = None, |
| 2503 | ) -> schema.DiscoveryReport: |
| 2504 | """Annotate + record the discovery queue, degrading a broken research.db |
| 2505 | (locked, read-only dir, corrupt) to a stderr warning: a queue failure |
| 2506 | must never destroy a finished pipeline run or the protocol's final |
| 2507 | brief. Shared verbatim by the one-shot and finalize paths.""" |
| 2508 | try: |
| 2509 | return _annotate_and_record_discovery_queue( |
| 2510 | report, args, config, run_ref=run_ref, |
| 2511 | ) |
| 2512 | except (sqlite3.Error, OSError) as exc: |
| 2513 | sys.stderr.write( |
| 2514 | f"[last30days] Warning: discovery queue unavailable ({exc}); " |
| 2515 | "continuing without queue annotations.\n" |
| 2516 | ) |
| 2517 | return report |
| 2518 | |
| 2519 | |
| 2520 | def _emit_and_save_discovery_report( |
| 2521 | report: schema.DiscoveryReport, |
| 2522 | args: argparse.Namespace, |
| 2523 | domain: str, |
| 2524 | ) -> None: |
| 2525 | """Render a discovery report per --emit, honor --output/--save-dir, and |
| 2526 | print it. Shared verbatim by the one-shot and finalize paths.""" |
| 2527 | if args.emit == "json": |
| 2528 | payload = schema.to_dict(report) if args.json_profile == "raw" else schema.to_discovery_export(report) |
| 2529 | rendered = json.dumps(payload, indent=2, sort_keys=True) |
| 2530 | else: |
| 2531 | rendered = render.render_discovery(report) |
| 2532 | |
| 2533 | if args.output: |
| 2534 | output_path = save_rendered_output(rendered, args.output) |
| 2535 | sys.stderr.write(f"[last30days] Saved output to {output_path}\n") |
| 2536 | if args.save_dir and not pipeline.is_blank_save_dir(args.save_dir): |
| 2537 | save_path = _save_discovery_output( |
| 2538 | rendered, |
| 2539 | domain=domain or "trending", |
| 2540 | emit=args.emit, |
| 2541 | save_dir=args.save_dir, |
| 2542 | suffix=args.save_suffix or "", |
| 2543 | ) |
| 2544 | sys.stderr.write(f"[last30days] Saved output to {save_path}\n") |
| 2545 | print(rendered) |
| 2546 | |
| 2547 | |
| 2548 | def _discovery_strict_exit_code( |
| 2549 | source_status: dict[str, schema.SourceOutcome], |
| 2550 | config: dict[str, object], |
| 2551 | ) -> int: |
| 2552 | """The ONE LAST30DAYS_STRICT_EXIT evaluation for every discovery |
| 2553 | invocation - the one-shot and all three protocol legs (issue #384's |
| 2554 | discovery counterpart). Rendering/output already happened by the time |
| 2555 | this runs; only the exit code shifts to 3 when strict exit is on and any |
| 2556 | source outcome is neither clean nor an expected skip.""" |
| 2557 | strict = str(config.get("LAST30DAYS_STRICT_EXIT") or "").strip().lower() |
| 2558 | if strict not in {"1", "true", "yes", "on"}: |
| 2559 | return 0 |
| 2560 | degraded = sorted( |
| 2561 | source for source, outcome in (source_status or {}).items() |
| 2562 | if outcome.state not in _STRICT_EXIT_OK_STATES |
| 2563 | ) |
| 2564 | if not degraded: |
| 2565 | return 0 |
| 2566 | sys.stdout.flush() |
| 2567 | sys.stderr.write( |
| 2568 | f"{health.STRICT_EXIT_PREFIX}{', '.join(degraded)}\n" |
| 2569 | ) |
| 2570 | sys.stderr.flush() |
| 2571 | return health.STRICT_EXIT_CODE |
| 2572 | |
| 2573 | |
| 2574 | def _require_discover_mock_parity( |
| 2575 | loaded_mock: bool, |
| 2576 | args_mock: bool, |
| 2577 | *, |
| 2578 | label: str, |
| 2579 | path: Path | None, |
| 2580 | ) -> None: |
| 2581 | """A protocol leg's --mock flag must match the loaded handoff file's |
| 2582 | stamped provenance: mock-born state finalized by a real run would fake a |
| 2583 | real brief from fixture data, and real state finalized by --mock would |
| 2584 | silently drop the round's queue write. Mismatch is a contract failure |
| 2585 | (exit 2 via HandoffContractError).""" |
| 2586 | if bool(loaded_mock) == bool(args_mock): |
| 2587 | return |
| 2588 | location = str(path) if path is not None else "(unknown path)" |
| 2589 | if loaded_mock: |
| 2590 | raise discovery_handoff.HandoffContractError( |
| 2591 | f"{label} {location} is mock-born (a --mock leg wrote it): " |
| 2592 | "mock-born state cannot be finalized by a real run. Re-run this " |
| 2593 | "leg with --mock, or start a fresh real `--discover " |
| 2594 | "--nominate-only` sweep." |
| 2595 | ) |
| 2596 | raise discovery_handoff.HandoffContractError( |
| 2597 | f"{label} {location} was written by a real run: real state " |
| 2598 | "cannot be finalized by a --mock run. Drop --mock, or start a fresh " |
| 2599 | "`--discover --nominate-only --mock` sweep." |
| 2600 | ) |
| 2601 | |
| 2602 | |
| 2603 | def _run_queue_list(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 2604 | """List uncovered surfaced topics from the persistent discovery queue.""" |
| 2605 | import store |
| 2606 | |
| 2607 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 2608 | if save_dir_exit is not None: |
| 2609 | return save_dir_exit |
| 2610 | db_path = _scoped_store_db(args) |
| 2611 | if not Path(db_path or store.DB_PATH).exists(): |
| 2612 | print("Discovery queue is empty - no discovery run has recorded topics yet.") |
| 2613 | return 0 |
| 2614 | with store.scoped_db(db_path): |
| 2615 | rows = store.list_discovery_queue(status="surfaced") |
| 2616 | if not rows: |
| 2617 | # An existing db with zero queue rows (e.g. created via --store) |
| 2618 | # means no discovery run has recorded anything - only claim |
| 2619 | # "every topic is covered" when covered rows actually exist. |
| 2620 | if store.list_discovery_queue(): |
| 2621 | print("Discovery queue is empty - every surfaced topic is marked covered.") |
| 2622 | else: |
| 2623 | print("Discovery queue is empty - no discovery run has recorded topics yet.") |
| 2624 | return 0 |
| 2625 | |
| 2626 | headers = ("name", "domain", "surface_count", "last_surfaced", "status") |
| 2627 | table = [ |
| 2628 | ( |
| 2629 | str(row["name"]), |
| 2630 | str(row["domain"] or "-"), |
| 2631 | str(row["surface_count"]), |
| 2632 | str(row["last_surfaced"]), |
| 2633 | str(row["status"]), |
| 2634 | ) |
| 2635 | for row in rows |
| 2636 | ] |
| 2637 | widths = [ |
| 2638 | max(len(headers[column]), *(len(row[column]) for row in table)) |
| 2639 | for column in range(len(headers)) |
| 2640 | ] |
| 2641 | lines = [ |
| 2642 | " ".join(header.ljust(widths[i]) for i, header in enumerate(headers)).rstrip(), |
| 2643 | " ".join("-" * widths[i] for i in range(len(headers))), |
| 2644 | ] |
| 2645 | lines.extend( |
| 2646 | " ".join(row[i].ljust(widths[i]) for i in range(len(headers))).rstrip() |
| 2647 | for row in table |
| 2648 | ) |
| 2649 | print("\n".join(lines)) |
| 2650 | return 0 |
| 2651 | |
| 2652 | |
| 2653 | def _run_queue_cover( |
| 2654 | args: argparse.Namespace, |
| 2655 | config: dict[str, object], |
| 2656 | name: str, |
| 2657 | ) -> int: |
| 2658 | """Mark a queued discovery topic covered; unknown names error loudly.""" |
| 2659 | import store |
| 2660 | |
| 2661 | if not name: |
| 2662 | sys.stderr.write( |
| 2663 | "[last30days] queue cover requires a topic name: " |
| 2664 | 'queue cover "<topic name>".\n' |
| 2665 | ) |
| 2666 | return 2 |
| 2667 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 2668 | if save_dir_exit is not None: |
| 2669 | return save_dir_exit |
| 2670 | db_path = _scoped_store_db(args) |
| 2671 | if not Path(db_path or store.DB_PATH).exists(): |
| 2672 | sys.stderr.write( |
| 2673 | f"[last30days] No queued topic named {name!r}: the discovery queue " |
| 2674 | "is empty (no discovery run has recorded topics yet).\n" |
| 2675 | ) |
| 2676 | return 2 |
| 2677 | with store.scoped_db(db_path): |
| 2678 | row = store.mark_discovery_covered( |
| 2679 | name, as_of=datetime.date.today().isoformat() |
| 2680 | ) |
| 2681 | if row is None: |
| 2682 | sys.stderr.write( |
| 2683 | f"[last30days] No queued topic named {name!r}. Covering requires " |
| 2684 | "the exact topic name; run 'queue list' to see queued names.\n" |
| 2685 | ) |
| 2686 | return 2 |
| 2687 | print(f"Marked covered: {row['name']} (covered {row['covered_at']})") |
| 2688 | return 0 |
| 2689 | |
| 2690 | |
| 2691 | def _resolve_discovery_source_boundary( |
| 2692 | args: argparse.Namespace, config: dict[str, object], |
| 2693 | ) -> tuple[list[str] | None, list[str] | None] | None: |
| 2694 | """Resolve the discovery sweep's source lists from the user's boundary. |
| 2695 | |
| 2696 | Returns ``(listing_sources, enrichment_boundary)`` - the discovery-capable |
| 2697 | subset for the sweep, and the user's ORIGINAL boundary honored by the |
| 2698 | per-topic research passes (which reach beyond the listing feeds - e.g. |
| 2699 | Techmeme, arXiv, YouTube, Polymarket); both None mean every available |
| 2700 | source. Returns None (after writing the exit-2 error) when the configured |
| 2701 | boundary leaves nothing to sweep: silently widening to all feeds would |
| 2702 | query sources the user filtered out. |
| 2703 | """ |
| 2704 | requested_sources = resolve_requested_sources(args.search, config) |
| 2705 | enrich_requested_sources = list(requested_sources) if requested_sources else None |
| 2706 | if requested_sources: |
| 2707 | discovery_sources = [ |
| 2708 | source for source in requested_sources |
| 2709 | if source in pipeline.DISCOVERY_SOURCES |
| 2710 | ] |
| 2711 | if not discovery_sources: |
| 2712 | origin = "--search" if args.search is not None else "LAST30DAYS_DEFAULT_SEARCH" |
| 2713 | sys.stderr.write( |
| 2714 | f"[last30days] {origin} has no discovery-capable sources " |
| 2715 | f"(unsupported: {', '.join(requested_sources)}); discovery " |
| 2716 | f"sweeps use: {', '.join(pipeline.DISCOVERY_SOURCES)}. Pass " |
| 2717 | "--search with one of those (or clear the source filter) to " |
| 2718 | "run a sweep.\n" |
| 2719 | ) |
| 2720 | return None |
| 2721 | requested_sources = discovery_sources |
| 2722 | return requested_sources, enrich_requested_sources |
| 2723 | |
| 2724 | |
| 2725 | def _discover_subreddits(args: argparse.Namespace) -> list[str] | None: |
| 2726 | return ( |
| 2727 | [value.strip().removeprefix("r/") for value in args.subreddits.split(",") if value.strip()] |
| 2728 | if args.subreddits else None |
| 2729 | ) |
| 2730 | |
| 2731 | |
| 2732 | def _discover_domain(args: argparse.Namespace) -> str: |
| 2733 | """The whitespace-normalized discovery domain; empty = global trending.""" |
| 2734 | return " ".join(str(args.discover or "").split()) |
| 2735 | |
| 2736 | |
| 2737 | def _run_discover(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 2738 | domain = _discover_domain(args) |
| 2739 | # Empty domain = global trending: sweep every river feed's hot list with no |
| 2740 | # keyword gate. The confidence floor is what keeps junk out, not a keyword. |
| 2741 | # (--as-of and HTML rejection live in _main's shared --discover dispatch, |
| 2742 | # so every leg - one-shot or protocol - applies the same guards.) |
| 2743 | if args.synthesis_file: |
| 2744 | sys.stderr.write("[last30days] Warning: --synthesis-file is not used by discovery mode.\n") |
| 2745 | |
| 2746 | boundary = _resolve_discovery_source_boundary(args, config) |
| 2747 | if boundary is None: |
| 2748 | return 2 |
| 2749 | requested_sources, enrich_requested_sources = boundary |
| 2750 | subreddits = _discover_subreddits(args) |
| 2751 | depth = "deep" if args.deep else "quick" if args.quick else "default" |
| 2752 | try: |
| 2753 | report = pipeline.run_discover( |
| 2754 | domain=domain, |
| 2755 | config=config, |
| 2756 | depth=depth, |
| 2757 | requested_sources=requested_sources, |
| 2758 | mock=args.mock, |
| 2759 | subreddits=subreddits, |
| 2760 | lookback_days=args.lookback_days or 30, |
| 2761 | as_of_date=args.as_of_date, |
| 2762 | enrich=not args.discover_shallow, |
| 2763 | enrich_requested_sources=enrich_requested_sources, |
| 2764 | ) |
| 2765 | except ValueError as exc: |
| 2766 | sys.stderr.write(f"[last30days] {exc}\n") |
| 2767 | return 2 |
| 2768 | |
| 2769 | # Persistent topic queue: annotate this report from prior surfacings, then |
| 2770 | # record this run's surfacings - BEFORE rendering/export so the Pipeline |
| 2771 | # line and the JSON queue fields see the annotations. Mock runs stay 100% |
| 2772 | # side-effect-free. |
| 2773 | if not args.mock: |
| 2774 | report = _record_discovery_queue_safely(report, args, config) |
| 2775 | |
| 2776 | _emit_and_save_discovery_report(report, args, domain) |
| 2777 | return _discovery_strict_exit_code(report.source_status, config) |
| 2778 | |
| 2779 | |
| 2780 | def _discover_handoff_state_dir(args: argparse.Namespace) -> Path | None: |
| 2781 | """One resolver for every protocol leg's handoff files: the save dir when |
| 2782 | given (mirroring _scoped_store_db's scoping), else the config dir - the |
| 2783 | same base _last_report_cache_path uses. args.save_dir is read AFTER the |
| 2784 | LAST30DAYS_MEMORY_DIR fallback in _main resolved it.""" |
| 2785 | return discovery_handoff.handoff_state_dir( |
| 2786 | getattr(args, "save_dir", None), env.CONFIG_DIR |
| 2787 | ) |
| 2788 | |
| 2789 | |
| 2790 | def _run_discover_nominate(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 2791 | """Protocol leg 1: sweep the listings, build the full judge pool, write |
| 2792 | the nominations bundle, and print the host-facing judging digest. |
| 2793 | |
| 2794 | No stage-1 judge, enrichment, confidence floor, or queue writes happen on |
| 2795 | this leg - the host judges from the bundle and leg 2 (--judgments) |
| 2796 | resumes from it. A zero-nomination sweep short-circuits to the existing |
| 2797 | nothing-solid brief with NO bundle written: there is nothing to judge. |
| 2798 | Writing a fresh bundle starts a NEW protocol round, so any pending |
| 2799 | report left by a prior round is deleted alongside it. |
| 2800 | """ |
| 2801 | domain = _discover_domain(args) |
| 2802 | boundary = _resolve_discovery_source_boundary(args, config) |
| 2803 | if boundary is None: |
| 2804 | return 2 |
| 2805 | requested_sources, enrich_requested_sources = boundary |
| 2806 | lookback_days = 30 if args.lookback_days is None else args.lookback_days |
| 2807 | discovery_handoff.validate_lookback_days(lookback_days) |
| 2808 | try: |
| 2809 | result = pipeline.run_discover_nominate( |
| 2810 | domain=domain, |
| 2811 | config=config, |
| 2812 | depth="deep" if args.deep else "quick" if args.quick else "default", |
| 2813 | requested_sources=requested_sources, |
| 2814 | mock=args.mock, |
| 2815 | subreddits=_discover_subreddits(args), |
| 2816 | lookback_days=lookback_days, |
| 2817 | as_of_date=args.as_of_date, |
| 2818 | ) |
| 2819 | except ValueError as exc: |
| 2820 | sys.stderr.write(f"[last30days] {exc}\n") |
| 2821 | return 2 |
| 2822 | |
| 2823 | if not result.pool: |
| 2824 | print(render.render_discovery(pipeline.nominate_nothing_solid_report(result))) |
| 2825 | return _discovery_strict_exit_code(result.source_status, config) |
| 2826 | |
| 2827 | entries = [ |
| 2828 | discovery_handoff.PoolEntry( |
| 2829 | nomination=nomination, |
| 2830 | cluster_id=cluster_id, |
| 2831 | # No provider runs on this leg, so the nomination's name and junk |
| 2832 | # flag ARE the topic_shape heuristics - stored on the row as |
| 2833 | # leg 2's fallback for anything the host leaves unjudged. |
| 2834 | heuristic_name=nomination.name, |
| 2835 | heuristic_junk=nomination.junk_shape, |
| 2836 | ) |
| 2837 | for nomination, cluster_id in result.pool |
| 2838 | ] |
| 2839 | bundle = discovery_handoff.write_nominations_bundle( |
| 2840 | entries, |
| 2841 | domain=result.plan.domain, |
| 2842 | tier="shallow" if args.discover_shallow else "deep", |
| 2843 | from_date=result.from_date, |
| 2844 | to_date=result.to_date, |
| 2845 | lookback_days=lookback_days, |
| 2846 | enrichment_source_boundary=enrich_requested_sources, |
| 2847 | requested_sources=requested_sources, |
| 2848 | # The sweep's finalized per-source outcomes ride the bundle so legs |
| 2849 | # 2-3 report degraded coverage instead of silently reading clean; the |
| 2850 | # mock stamp keeps mock-born and real state from cross-finalizing. |
| 2851 | source_status=result.source_status, |
| 2852 | warnings=result.warnings, |
| 2853 | mock=args.mock, |
| 2854 | # Same resolution as _discover_handoff_state_dir: save dir when |
| 2855 | # given, else the config dir. |
| 2856 | save_dir=getattr(args, "save_dir", None), |
| 2857 | config_dir=env.CONFIG_DIR, |
| 2858 | ) |
| 2859 | # A fresh bundle starts a NEW protocol round: a pending report left by a |
| 2860 | # prior round is cross-round state a bare --finalize could silently |
| 2861 | # consume - delete it (missing file is a no-op). |
| 2862 | state_dir = _discover_handoff_state_dir(args) |
| 2863 | if state_dir is not None: |
| 2864 | discovery_handoff.pending_report_path(state_dir).unlink(missing_ok=True) |
| 2865 | print(discovery_handoff.build_host_digest(bundle)) |
| 2866 | print( |
| 2867 | "\nJudgments file schema (leg 2): " |
| 2868 | f'{{"bundle_id": "{bundle.bundle_id}", "judgments": ' |
| 2869 | '[{"id": "n1", "name": "<short topic name>", "junk": false, ' |
| 2870 | '"worthiness": 0-100}, ...]}. ' |
| 2871 | "Then resume with: --discover --judgments <path>." |
| 2872 | ) |
| 2873 | return _discovery_strict_exit_code(result.source_status, config) |
| 2874 | |
| 2875 | |
| 2876 | def _run_discover_resume(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 2877 | """Protocol leg 2: resume from the nominations bundle, apply the host |
| 2878 | judgments file, run the deep per-topic research pass, and persist the |
| 2879 | ranked result as the pending report for leg 3 (--finalize). |
| 2880 | |
| 2881 | Contract failures (missing/stale bundle, judgments not bound to it, a |
| 2882 | bundle whose mock provenance disagrees with this run's --mock flag, an |
| 2883 | unwritable pending-report path) raise HandoffContractError and map to |
| 2884 | exit 2 in _run_discover_protocol_leg. Zero floor survivors renders the |
| 2885 | nothing-solid brief right here (clearing any stale prior-round pending |
| 2886 | file): no pending file, no leg 3. No queue writes and no artifact saves |
| 2887 | happen on this leg - the topic queue and the rendered brief belong to |
| 2888 | leg 3. |
| 2889 | """ |
| 2890 | save_dir = getattr(args, "save_dir", None) |
| 2891 | bundle = discovery_handoff.read_nominations_bundle( |
| 2892 | save_dir=save_dir, config_dir=env.CONFIG_DIR, |
| 2893 | ) |
| 2894 | _require_discover_mock_parity( |
| 2895 | bundle.mock, args.mock, |
| 2896 | label="Nominations bundle", path=bundle.path, |
| 2897 | ) |
| 2898 | judgments = discovery_handoff.read_judgments( |
| 2899 | args.judgments, bundle, save_dir=save_dir, config_dir=env.CONFIG_DIR, |
| 2900 | ) |
| 2901 | result = pipeline.run_discover_resume( |
| 2902 | bundle, judgments, config=config, mock=args.mock, |
| 2903 | ) |
| 2904 | report = result.report |
| 2905 | |
| 2906 | if not report.topics: |
| 2907 | # Nothing cleared the floor: the honest brief ends the protocol here. |
| 2908 | # This round wrote no pending file, so a stale one from an earlier |
| 2909 | # round must not survive to feed a bare --finalize (missing file is |
| 2910 | # a no-op). |
| 2911 | state_dir = _discover_handoff_state_dir(args) |
| 2912 | if state_dir is not None: |
| 2913 | discovery_handoff.pending_report_path(state_dir).unlink(missing_ok=True) |
| 2914 | print(render.render_discovery(report)) |
| 2915 | return _discovery_strict_exit_code(report.source_status, config) |
| 2916 | |
| 2917 | state_dir = _discover_handoff_state_dir(args) |
| 2918 | if state_dir is None: |
| 2919 | # Unreachable in practice - reading the bundle above required one of |
| 2920 | # these locations - but kept as a loud contract error, not an assert. |
| 2921 | raise discovery_handoff.HandoffContractError( |
| 2922 | "No handoff location available to write the pending report: " |
| 2923 | "pass --save-dir or configure ~/.config/last30days/." |
| 2924 | ) |
| 2925 | pending_path = discovery_handoff.pending_report_path(state_dir) |
| 2926 | payload = { |
| 2927 | "kind": schema.DISCOVERY_PENDING_KIND, |
| 2928 | "schema_version": schema.DISCOVERY_PENDING_SCHEMA_VERSION, |
| 2929 | "bundle_id": bundle.bundle_id, |
| 2930 | # Fresh TTL clock: leg 3 measures staleness from THIS resume run, |
| 2931 | # not from the leg-1 sweep. |
| 2932 | "generated_at": report.generated_at, |
| 2933 | # Same run_ref format the queue records (leg 3 replays it verbatim). |
| 2934 | "run_ref": f"discover:{report.domain or 'trending'}:{report.generated_at}", |
| 2935 | # Leg-2 provenance: leg 3 refuses to finalize across the mock/real |
| 2936 | # boundary in either direction. |
| 2937 | "mock": bool(args.mock), |
| 2938 | # Full schema round-trip (the _write_last_run precedent): leg 3 |
| 2939 | # rebuilds the report from this dict instead of re-running anything. |
| 2940 | "report": schema.to_dict(report), |
| 2941 | "angle_inputs": result.angle_inputs, |
| 2942 | } |
| 2943 | # ONE post-loop write from the main thread; enrichment workers are daemon |
| 2944 | # threads and never touch disk. |
| 2945 | try: |
| 2946 | state_dir.mkdir(parents=True, exist_ok=True) |
| 2947 | pending_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") |
| 2948 | except OSError as exc: |
| 2949 | # A locked/read-only/full disk is the protocol's clean exit-2 path, |
| 2950 | # never a traceback (same contract as the bundle write). |
| 2951 | raise discovery_handoff.HandoffContractError( |
| 2952 | f"Could not write pending discovery report {pending_path}: {exc}" |
| 2953 | ) from exc |
| 2954 | |
| 2955 | print( |
| 2956 | f"Judged discovery resume: {len(report.topics)} topic" |
| 2957 | f"{'s' if len(report.topics) != 1 else ''} cleared the floor " |
| 2958 | f"(bundle_id {bundle.bundle_id})." |
| 2959 | ) |
| 2960 | print(f"Pending report: {pending_path}") |
| 2961 | print("\nAngle inputs by nomination id:") |
| 2962 | print(json.dumps(result.angle_inputs, indent=2)) |
| 2963 | print( |
| 2964 | "\nWrite the angles file (leg 3): " |
| 2965 | f'{{"bundle_id": "{bundle.bundle_id}", "angles": ' |
| 2966 | '[{"id": "n1", "podcast": "<one-sentence hook>", ' |
| 2967 | '"x_article": "<one-sentence hook>"}, ...]} - one row per topic id ' |
| 2968 | "above.\n" |
| 2969 | "Then finalize with: --discover --finalize --angles <path>." |
| 2970 | ) |
| 2971 | return _discovery_strict_exit_code(report.source_status, config) |
| 2972 | |
| 2973 | |
| 2974 | def _run_discover_finalize(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 2975 | """Protocol leg 3: load the leg-2 pending report, apply host angles, |
| 2976 | render the final brief, save discovery artifacts, and record the topic |
| 2977 | queue. The cheap offline leg - no sweep, no enrichment, no providers, |
| 2978 | no network; everything renders from the pending report. (HTML/--as-of |
| 2979 | rejection lives in _main's shared --discover dispatch.) |
| 2980 | |
| 2981 | Contract failures (missing/stale/mismatched pending report or angles) |
| 2982 | raise HandoffContractError and map to exit 2 in |
| 2983 | _run_discover_protocol_leg. The pending file is deliberately LEFT IN |
| 2984 | PLACE on success: a finalize retry with a corrected angles file must |
| 2985 | keep working within the TTL, and the queue records under the pending |
| 2986 | report's leg-2 run_ref, so retries never double-count a surfacing. |
| 2987 | Mock finalize renders identically but writes no queue rows. |
| 2988 | """ |
| 2989 | import dataclasses |
| 2990 | |
| 2991 | save_dir = getattr(args, "save_dir", None) |
| 2992 | pending = discovery_handoff.read_pending_report( |
| 2993 | save_dir=save_dir, config_dir=env.CONFIG_DIR, |
| 2994 | ) |
| 2995 | _require_discover_mock_parity( |
| 2996 | pending.mock, args.mock, |
| 2997 | label="Pending discovery report", path=pending.path, |
| 2998 | ) |
| 2999 | angles = discovery_handoff.read_angles( |
| 3000 | args.angles, pending, save_dir=save_dir, config_dir=env.CONFIG_DIR, |
| 3001 | ) |
| 3002 | try: |
| 3003 | report = schema.discovery_report_from_dict(pending.report) |
| 3004 | except (KeyError, TypeError, ValueError) as exc: |
| 3005 | # The envelope validated but the report body is structurally |
| 3006 | # incomplete: a contract failure with the resume remedy, never a |
| 3007 | # traceback out of the finalize leg. |
| 3008 | raise discovery_handoff.HandoffContractError( |
| 3009 | f"Pending discovery report {pending.path} carries a malformed " |
| 3010 | f"report body ({type(exc).__name__}: {exc}). " |
| 3011 | f"{discovery_handoff._RESUME_REMEDY}" |
| 3012 | ) from exc |
| 3013 | |
| 3014 | if angles: |
| 3015 | # Host angles are keyed by nomination id; the pending report's |
| 3016 | # angle_inputs mapping carries each surviving id's applied topic |
| 3017 | # name, which is how angles land on the right DiscoveryTopic. |
| 3018 | angles_by_name = { |
| 3019 | name: host |
| 3020 | for nomination_id, host in angles.items() |
| 3021 | if (name := (pending.angle_inputs.get(nomination_id) or {}).get("name")) |
| 3022 | } |
| 3023 | report = dataclasses.replace(report, topics=[ |
| 3024 | dataclasses.replace( |
| 3025 | topic, |
| 3026 | podcast_angle=host.podcast, |
| 3027 | x_article_angle=host.x_article, |
| 3028 | ) |
| 3029 | if (host := angles_by_name.get(topic.name)) is not None |
| 3030 | else topic |
| 3031 | for topic in report.topics |
| 3032 | ]) |
| 3033 | |
| 3034 | # Persistent topic queue: the protocol's ONE queue write happens here, |
| 3035 | # under the leg-2 run identity (pending.run_ref) so finalize retries are |
| 3036 | # idempotent. Mock runs stay 100% side-effect-free. |
| 3037 | if not args.mock: |
| 3038 | report = _record_discovery_queue_safely( |
| 3039 | report, args, config, run_ref=pending.run_ref or None, |
| 3040 | ) |
| 3041 | |
| 3042 | _emit_and_save_discovery_report(report, args, report.domain) |
| 3043 | return _discovery_strict_exit_code(report.source_status, config) |
| 3044 | |
| 3045 | |
| 3046 | def _run_discover_protocol_leg( |
| 3047 | args: argparse.Namespace, config: dict[str, object] |
| 3048 | ) -> int: |
| 3049 | """Route one validated protocol invocation to its leg. Contract failures |
| 3050 | (unreadable/stale/mismatched handoff files) map to stderr + exit 2 here, |
| 3051 | so the leg bodies (U3-U5) raise HandoffContractError freely.""" |
| 3052 | try: |
| 3053 | if args.nominate_only: |
| 3054 | return _run_discover_nominate(args, config) |
| 3055 | # --judgments dispatch keys on flag presence (is not None), matching |
| 3056 | # the --discover convention: never on the path string's truthiness. |
| 3057 | if args.judgments is not None: |
| 3058 | return _run_discover_resume(args, config) |
| 3059 | return _run_discover_finalize(args, config) |
| 3060 | except discovery_handoff.HandoffContractError as exc: |
| 3061 | sys.stderr.write(f"[last30days] {exc.message}\n") |
| 3062 | return 2 |
| 3063 | |
| 3064 | |
| 3065 | _STRICT_EXIT_OK_STATES = {"ok", "no-results", "skipped-unconfigured"} |
| 3066 | |
| 3067 | |
| 3068 | def _strict_exit_code( |
| 3069 | report: schema.Report, |
| 3070 | entity_reports: list[tuple[str, schema.Report]] | None, |
| 3071 | config: dict[str, object], |
| 3072 | ) -> int: |
| 3073 | """Opt-in machine-detectable degraded-run signal (issue #384). |
| 3074 | |
| 3075 | When LAST30DAYS_STRICT_EXIT is truthy, a run whose report carries any |
| 3076 | source outcome that is neither clean nor a plain no-results exits 3 so |
| 3077 | cron/CI wrappers can distinguish degraded coverage from success. Default |
| 3078 | behavior (exit 0, warning rendered in the report footer) is unchanged. |
| 3079 | """ |
| 3080 | raw = str(config.get("LAST30DAYS_STRICT_EXIT") or "").strip().lower() |
| 3081 | if raw not in {"1", "true", "yes", "on"}: |
| 3082 | return 0 |
| 3083 | reports = [report] + [rep for _, rep in (entity_reports or [])] |
| 3084 | degraded = sorted({ |
| 3085 | name |
| 3086 | for rep in reports |
| 3087 | for name, outcome in (rep.source_status or {}).items() |
| 3088 | if outcome.state not in _STRICT_EXIT_OK_STATES |
| 3089 | }) |
| 3090 | if not degraded: |
| 3091 | return 0 |
| 3092 | sys.stdout.flush() |
| 3093 | sys.stderr.write( |
| 3094 | f"{health.STRICT_EXIT_PREFIX}{', '.join(degraded)}\n" |
| 3095 | ) |
| 3096 | sys.stderr.flush() |
| 3097 | return health.STRICT_EXIT_CODE |
| 3098 | |
| 3099 | |
| 3100 | def _audience_register_for_run( |
| 3101 | args: argparse.Namespace, |
| 3102 | config: dict[str, object], |
| 3103 | entity_reports: list[tuple[str, schema.Report]] | None, |
| 3104 | ) -> registers.AudienceRegister: |
| 3105 | """Resolve CLI > config for single-topic standard brief renderers.""" |
| 3106 | |
| 3107 | from lib import planner |
| 3108 | |
| 3109 | topic = " ".join(getattr(args, "topic", [])).strip() |
| 3110 | comparison_topic_requested = bool( |
| 3111 | len(planner._comparison_entities(topic)) >= 2 |
| 3112 | or args.competitors is not None |
| 3113 | or args.competitors_list |
| 3114 | or args.competitors_plan |
| 3115 | ) |
| 3116 | if ( |
| 3117 | entity_reports |
| 3118 | or comparison_topic_requested |
| 3119 | or args.drill |
| 3120 | or args.emit not in {"compact", "md", "html"} |
| 3121 | ): |
| 3122 | return registers.get_register() |
| 3123 | explicit = getattr(args, "register", None) |
| 3124 | configured = config.get("LAST30DAYS_REGISTER") |
| 3125 | name = explicit or (str(configured) if configured else "default") |
| 3126 | # Preserve configs written by the pre-register ELI5 follow-up command. |
| 3127 | legacy_eli5 = str(config.get("ELI5_MODE") or "").strip().lower() |
| 3128 | if not explicit and not configured and legacy_eli5 in {"1", "true", "yes", "on"}: |
| 3129 | name = "eli5" |
| 3130 | return registers.get_register(name) |
| 3131 | |
| 3132 | |
| 3133 | def _render_save_and_print( |
| 3134 | args: argparse.Namespace, |
| 3135 | report: schema.Report, |
| 3136 | entity_reports: list[tuple[str, schema.Report]] | None, |
| 3137 | synthesis_md: str | None, |
| 3138 | config: dict[str, object], |
| 3139 | ) -> int: |
| 3140 | publish_exit = _validate_publish_html(args) |
| 3141 | if publish_exit is not None: |
| 3142 | return publish_exit |
| 3143 | comp_emit_exit = _validate_comparison_emit(args, is_comparison=bool(entity_reports)) |
| 3144 | if comp_emit_exit is not None: |
| 3145 | return comp_emit_exit |
| 3146 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 3147 | if save_dir_exit is not None: |
| 3148 | return save_dir_exit |
| 3149 | fun_level = str(config.get("FUN_LEVEL", "medium")).lower() |
| 3150 | try: |
| 3151 | audience = _audience_register_for_run(args, config, entity_reports) |
| 3152 | except ValueError as exc: |
| 3153 | sys.stderr.write(f"[last30days] {exc}\n") |
| 3154 | return 2 |
| 3155 | if audience.name != "default": |
| 3156 | sys.stderr.write(f"[last30days] Audience register: {audience.name}\n") |
| 3157 | sys.stderr.flush() |
| 3158 | # Comparison HTML is the one case where the saved file's title and content |
| 3159 | # have to be overridden away from the leading entity's report. Compute the |
| 3160 | # gate once so the footer-display and save-output paths can't disagree. |
| 3161 | is_comparison_html = bool(entity_reports) and args.emit == "html" |
| 3162 | footer_save_path = None |
| 3163 | if args.output: |
| 3164 | footer_save_path = compute_output_path_display(args.output) |
| 3165 | elif args.save_dir: |
| 3166 | save_topic_for_display = comparison_topic(entity_reports) if is_comparison_html else report.topic |
| 3167 | footer_save_path = compute_save_path_display( |
| 3168 | args.save_dir, save_topic_for_display, args.save_suffix or "", args.emit |
| 3169 | ) |
| 3170 | |
| 3171 | if entity_reports: |
| 3172 | rendered = emit_comparison_output( |
| 3173 | entity_reports, |
| 3174 | args.emit, |
| 3175 | fun_level=fun_level, |
| 3176 | save_path=footer_save_path, |
| 3177 | synthesis_md=synthesis_md, |
| 3178 | json_profile=args.json_profile, |
| 3179 | ) |
| 3180 | else: |
| 3181 | rendered = emit_output( |
| 3182 | report, |
| 3183 | args.emit, |
| 3184 | fun_level=fun_level, |
| 3185 | save_path=footer_save_path, |
| 3186 | synthesis_md=synthesis_md, |
| 3187 | json_profile=args.json_profile, |
| 3188 | register=audience.name, |
| 3189 | ) |
| 3190 | has_private_corpus = _report_has_private_corpus(report) or bool( |
| 3191 | entity_reports |
| 3192 | and any(_report_has_private_corpus(entity) for _label, entity in entity_reports) |
| 3193 | ) |
| 3194 | private_saved_format = has_private_corpus |
| 3195 | publish_companion_paths: list[Path] = [] |
| 3196 | if args.output: |
| 3197 | output_path = save_rendered_output( |
| 3198 | rendered, |
| 3199 | args.output, |
| 3200 | private=private_saved_format, |
| 3201 | ) |
| 3202 | if args.emit == "html": |
| 3203 | publish_companion_paths.append(output_path) |
| 3204 | sys.stderr.write(f"[last30days] Saved output to {output_path}\n") |
| 3205 | sys.stderr.flush() |
| 3206 | if args.save_dir: |
| 3207 | # Save the main topic's raw file (single-entity or comparison main). |
| 3208 | # Bind the render to the path save_output actually allocates so the |
| 3209 | # saved report and stdout agree even when collision fallback is used. |
| 3210 | def _render_with_actual_path(actual_path: Path) -> str: |
| 3211 | nonlocal rendered |
| 3212 | display = compute_output_path_display(str(actual_path)) |
| 3213 | if entity_reports: |
| 3214 | rendered = emit_comparison_output( |
| 3215 | entity_reports, |
| 3216 | args.emit, |
| 3217 | fun_level=fun_level, |
| 3218 | save_path=display, |
| 3219 | synthesis_md=synthesis_md, |
| 3220 | json_profile=args.json_profile, |
| 3221 | ) |
| 3222 | else: |
| 3223 | rendered = emit_output( |
| 3224 | report, |
| 3225 | args.emit, |
| 3226 | fun_level=fun_level, |
| 3227 | save_path=display, |
| 3228 | synthesis_md=synthesis_md, |
| 3229 | json_profile=args.json_profile, |
| 3230 | register=audience.name, |
| 3231 | ) |
| 3232 | if args.emit not in {"json", "html"}: |
| 3233 | # Markdown saves keep the complete debug artifact (all clusters |
| 3234 | # and per-source items), matching the render_fn-less path in |
| 3235 | # save_output and the comparison peer saves. Saving the compact |
| 3236 | # stdout render instead made most collected evidence |
| 3237 | # unrecoverable from the raw file (#923). The stdout re-render |
| 3238 | # above still runs so the visible footer cites the real path, |
| 3239 | # and the saved artifact carries the same citation. |
| 3240 | return render.render_full(report, save_path=display) |
| 3241 | return rendered |
| 3242 | |
| 3243 | save_path = save_output( |
| 3244 | report, |
| 3245 | args.emit, |
| 3246 | args.save_dir, |
| 3247 | suffix=args.save_suffix or "", |
| 3248 | synthesis_md=synthesis_md, |
| 3249 | topic_override=comparison_topic(entity_reports) if is_comparison_html else None, |
| 3250 | json_profile=args.json_profile, |
| 3251 | register=audience.name, |
| 3252 | private=private_saved_format, |
| 3253 | render_fn=_render_with_actual_path, |
| 3254 | ) |
| 3255 | if args.emit == "html": |
| 3256 | publish_companion_paths.append(save_path) |
| 3257 | sys.stderr.write(f"[last30days] Saved output to {save_path}\n") |
| 3258 | comparison_peer_paths: list[Path] = [] |
| 3259 | # Competitor / vs-mode: also save a per-entity raw file for each peer. |
| 3260 | # Matches historical vs-mode behavior (N passes -> N save files). |
| 3261 | if entity_reports and len(entity_reports) > 1: |
| 3262 | for label, entity_report in entity_reports[1:]: |
| 3263 | peer_path = save_output( |
| 3264 | entity_report, args.emit, args.save_dir, |
| 3265 | suffix=args.save_suffix or "", |
| 3266 | synthesis_md=synthesis_md, |
| 3267 | json_profile=args.json_profile, |
| 3268 | private=_report_has_private_corpus(entity_report), |
| 3269 | ) |
| 3270 | comparison_peer_paths.append(peer_path) |
| 3271 | sys.stderr.write(f"[last30days] Saved output to {peer_path}\n") |
| 3272 | peers_display = ", ".join(str(path) for path in comparison_peer_paths) |
| 3273 | sys.stderr.write( |
| 3274 | f"[last30days] Comparison artifact set: main={save_path}; " |
| 3275 | f"peers={peers_display}\n" |
| 3276 | ) |
| 3277 | sys.stderr.flush() |
| 3278 | if args.publish_html: |
| 3279 | try: |
| 3280 | published_reports = [entity for _label, entity in entity_reports] if entity_reports else [report] |
| 3281 | publish_rendered = rendered |
| 3282 | if any(schema.report_has_corpus(entity) for entity in published_reports): |
| 3283 | sys.stderr.write( |
| 3284 | "[last30days] Excluding local corpus evidence and synthesis from published HTML.\n" |
| 3285 | ) |
| 3286 | if entity_reports: |
| 3287 | publish_rendered = emit_comparison_output( |
| 3288 | [ |
| 3289 | (label, schema.without_sources(entity, {"corpus"})) |
| 3290 | for label, entity in entity_reports |
| 3291 | ], |
| 3292 | "html", |
| 3293 | fun_level=fun_level, |
| 3294 | save_path=footer_save_path, |
| 3295 | synthesis_md=None, |
| 3296 | json_profile=args.json_profile, |
| 3297 | ) |
| 3298 | else: |
| 3299 | publish_rendered = emit_output( |
| 3300 | schema.without_sources(report, {"corpus"}), |
| 3301 | "html", |
| 3302 | fun_level=fun_level, |
| 3303 | save_path=footer_save_path, |
| 3304 | synthesis_md=None, |
| 3305 | json_profile=args.json_profile, |
| 3306 | register=audience.name, |
| 3307 | ) |
| 3308 | publish_result = publish_rendered_html( |
| 3309 | publish_rendered, |
| 3310 | password=_publish_password_for_args(args, config), |
| 3311 | companion_paths=publish_companion_paths, |
| 3312 | ) |
| 3313 | sys.stderr.write(f"[last30days] Published HTML to {publish_result['url']}\n") |
| 3314 | for warning in publish_result.get("_metadata_errors") or []: |
| 3315 | sys.stderr.write(f"[last30days] Publish metadata warning: {warning}\n") |
| 3316 | if publish_result.get("update_key"): |
| 3317 | sys.stderr.write( |
| 3318 | "[last30days] ht-ml.app returned an update key; not writing it " |
| 3319 | "to stdout, HTML, or publish metadata.\n" |
| 3320 | ) |
| 3321 | sys.stderr.flush() |
| 3322 | except Exception as exc: |
| 3323 | sys.stderr.write(f"[last30days] HTML publish failed: {exc}\n") |
| 3324 | sys.stderr.flush() |
| 3325 | checklist = _report_checklist_for_stdout(args, rendered, report, entity_reports, audience.name) |
| 3326 | if checklist: |
| 3327 | print(rendered + checklist, end="") |
| 3328 | else: |
| 3329 | print(rendered) |
| 3330 | return _strict_exit_code(report, entity_reports, config) |
| 3331 | |
| 3332 | |
| 3333 | def _report_checklist_for_stdout( |
| 3334 | args: argparse.Namespace, |
| 3335 | rendered: str, |
| 3336 | report: schema.Report, |
| 3337 | entity_reports: list[tuple[str, schema.Report]] | None, |
| 3338 | register: str, |
| 3339 | ) -> str: |
| 3340 | """The format checklist that follows compact stdout, or "" for any other |
| 3341 | output. It is added here, at the print, so no saved or ``--output`` file, |
| 3342 | no other emit mode and no renderer ever carries it. A hiring-signals run |
| 3343 | writes its own scoped report, which the checklist does not describe.""" |
| 3344 | if args.emit != "compact" or getattr(args, "hiring_signals", False): |
| 3345 | return "" |
| 3346 | return report_checklist.build( |
| 3347 | rendered, |
| 3348 | comparison=bool(entity_reports), |
| 3349 | recommendation=report_checklist.is_recommendation_run( |
| 3350 | report.query_plan.intent, report.topic, report.query_plan.raw_topic, |
| 3351 | ), |
| 3352 | register=register, |
| 3353 | ) |
| 3354 | |
| 3355 | |
| 3356 | def _propagate_config_to_environ(config: dict[str, object]) -> None: |
| 3357 | """Push relevant env keys to os.environ so provider modules can read them. |
| 3358 | |
| 3359 | The env.get_config() function reads from a .env file, but providers.py |
| 3360 | reads from os.environ directly. Without this, OPENAI_BASE_URL and |
| 3361 | XAI_BASE_URL overrides are silently ignored. This is a no-op for |
| 3362 | keys that are already set in process env. |
| 3363 | """ |
| 3364 | for key in ("OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL", "SCRAPECREATORS_BASE_URL"): |
| 3365 | val = config.get(key) |
| 3366 | if val and not os.environ.get(key): |
| 3367 | os.environ[key] = val |
| 3368 | |
| 3369 | |
| 3370 | _NON_AUTO_SETUP_FLAGS = frozenset({ |
| 3371 | "--openclaw", |
| 3372 | "--github", |
| 3373 | "--github-start", |
| 3374 | "--github-poll", |
| 3375 | "--device-auth", |
| 3376 | "--reddit-session", |
| 3377 | "--no-reddit-session", |
| 3378 | }) |
| 3379 | |
| 3380 | _SETUP_NO_SECRET_STORE_FLAGS = frozenset({ |
| 3381 | "--github", |
| 3382 | "--github-start", |
| 3383 | "--github-poll", |
| 3384 | "--device-auth", |
| 3385 | "--reddit-session", |
| 3386 | "--no-reddit-session", |
| 3387 | }) |
| 3388 | |
| 3389 | |
| 3390 | def _setup_is_non_auto(extra_argv: list[str]) -> bool: |
| 3391 | store_key_present, _, remaining = _split_store_key(extra_argv) |
| 3392 | if store_key_present: |
| 3393 | return True |
| 3394 | install_target, uninstall_target, remaining = _split_hook_flags(remaining) |
| 3395 | if install_target is not None or uninstall_target is not None: |
| 3396 | return True |
| 3397 | return any(flag in _NON_AUTO_SETUP_FLAGS for flag in remaining) |
| 3398 | |
| 3399 | |
| 3400 | def _setup_skips_secret_stores(extra_argv: list[str]) -> bool: |
| 3401 | store_key_present, _, remaining = _split_store_key(extra_argv) |
| 3402 | if store_key_present: |
| 3403 | return True |
| 3404 | install_target, uninstall_target, remaining = _split_hook_flags(remaining) |
| 3405 | if install_target is not None or uninstall_target is not None: |
| 3406 | return True |
| 3407 | # Mirror setup dispatch precedence: --openclaw runs before --reddit-session |
| 3408 | # and --github*/--device-auth, and reports stored provider keys. |
| 3409 | if "--openclaw" in remaining: |
| 3410 | return False |
| 3411 | return any(flag in _SETUP_NO_SECRET_STORE_FLAGS for flag in remaining) |
| 3412 | |
| 3413 | |
| 3414 | def _is_library_command(command_topic: str) -> bool: |
| 3415 | return ( |
| 3416 | command_topic == "library feed" |
| 3417 | or command_topic == "library harvest" |
| 3418 | or command_topic == "library search" |
| 3419 | or command_topic.startswith("library search ") |
| 3420 | ) |
| 3421 | |
| 3422 | |
| 3423 | def _is_queue_command(command_topic: str) -> bool: |
| 3424 | return ( |
| 3425 | command_topic == "queue list" |
| 3426 | or command_topic == "queue cover" |
| 3427 | or command_topic.startswith("queue cover ") |
| 3428 | ) |
| 3429 | |
| 3430 | |
| 3431 | def _is_admin_command(command_topic: str) -> bool: |
| 3432 | return ( |
| 3433 | command_topic in {"setup", "doctor"} |
| 3434 | or _is_library_command(command_topic) |
| 3435 | or _is_queue_command(command_topic) |
| 3436 | ) |
| 3437 | |
| 3438 | |
| 3439 | def _setup_has_fresh_browser_consent(args: argparse.Namespace, extra_argv: list[str]) -> bool: |
| 3440 | return ( |
| 3441 | not args.no_browser_cookies |
| 3442 | and not args.diagnose |
| 3443 | and not args.preflight |
| 3444 | and not _setup_is_non_auto(extra_argv) |
| 3445 | and "--allow-browser-cookies" in extra_argv |
| 3446 | ) |
| 3447 | |
| 3448 | |
| 3449 | USE_RECORDED_BROWSER_CONSENT_FLAG = "--use-recorded-browser-consent" |
| 3450 | |
| 3451 | SETUP_PASSTHROUGH_FLAGS = { |
| 3452 | "--allow-browser-cookies", |
| 3453 | USE_RECORDED_BROWSER_CONSENT_FLAG, |
| 3454 | "--device-auth", |
| 3455 | "--github", |
| 3456 | "--github-start", |
| 3457 | "--github-poll", |
| 3458 | "--install-hooks", |
| 3459 | "--openclaw", |
| 3460 | "--reddit-session", |
| 3461 | "--no-reddit-session", |
| 3462 | "--store-key", |
| 3463 | "--uninstall-hooks", |
| 3464 | } |
| 3465 | |
| 3466 | INSTALL_HOOKS_FLAG = "--install-hooks" |
| 3467 | UNINSTALL_HOOKS_FLAG = "--uninstall-hooks" |
| 3468 | |
| 3469 | |
| 3470 | def _split_hook_flags( |
| 3471 | extra_argv: list[str], |
| 3472 | ) -> tuple[str | None, str | None, list[str]]: |
| 3473 | """Pull optional-value ``--install-hooks [HOST]`` / ``--uninstall-hooks [HOST]``. |
| 3474 | |
| 3475 | Returns ``(install_target, uninstall_target, remaining)``. Each target is |
| 3476 | ``None`` when absent, ``""`` when passed bare (meaning all detected local |
| 3477 | harnesses), or the explicit host string when supplied. Callers MUST check |
| 3478 | ``is not None``, never truthiness. |
| 3479 | """ |
| 3480 | install_target: str | None = None |
| 3481 | uninstall_target: str | None = None |
| 3482 | remaining: list[str] = [] |
| 3483 | i = 0 |
| 3484 | while i < len(extra_argv): |
| 3485 | arg = extra_argv[i] |
| 3486 | if arg in (INSTALL_HOOKS_FLAG, UNINSTALL_HOOKS_FLAG): |
| 3487 | value = "" |
| 3488 | if i + 1 < len(extra_argv) and not extra_argv[i + 1].startswith("-"): |
| 3489 | value = extra_argv[i + 1] |
| 3490 | i += 2 |
| 3491 | else: |
| 3492 | i += 1 |
| 3493 | if arg == INSTALL_HOOKS_FLAG: |
| 3494 | install_target = value |
| 3495 | else: |
| 3496 | uninstall_target = value |
| 3497 | continue |
| 3498 | if arg.startswith(INSTALL_HOOKS_FLAG + "="): |
| 3499 | install_target = arg[len(INSTALL_HOOKS_FLAG) + 1 :] |
| 3500 | i += 1 |
| 3501 | continue |
| 3502 | if arg.startswith(UNINSTALL_HOOKS_FLAG + "="): |
| 3503 | uninstall_target = arg[len(UNINSTALL_HOOKS_FLAG) + 1 :] |
| 3504 | i += 1 |
| 3505 | continue |
| 3506 | remaining.append(arg) |
| 3507 | i += 1 |
| 3508 | return install_target, uninstall_target, remaining |
| 3509 | |
| 3510 | |
| 3511 | def _run_hook_setup( |
| 3512 | install_target: str | None, |
| 3513 | uninstall_target: str | None, |
| 3514 | ) -> int: |
| 3515 | from lib import hook_installer |
| 3516 | |
| 3517 | if install_target is not None and uninstall_target is not None: |
| 3518 | sys.stderr.write( |
| 3519 | "[last30days] pass --install-hooks or --uninstall-hooks, not both.\n" |
| 3520 | ) |
| 3521 | return 2 |
| 3522 | try: |
| 3523 | # Bare --install-hooks / --uninstall-hooks uses "" -> "all", so dispatch |
| 3524 | # checks `is not None` rather than string truthiness. |
| 3525 | if install_target is not None: |
| 3526 | result = hook_installer.install_hooks(install_target or "all") |
| 3527 | else: |
| 3528 | result = hook_installer.uninstall_hooks(uninstall_target or "all") |
| 3529 | except ValueError as exc: |
| 3530 | sys.stderr.write(f"[last30days] {exc}\n") |
| 3531 | return 2 |
| 3532 | print(json.dumps(result, indent=2, sort_keys=True)) |
| 3533 | return 0 |
| 3534 | |
| 3535 | STORE_KEY_FLAG = "--store-key" |
| 3536 | |
| 3537 | |
| 3538 | def _split_store_key(extra_argv: list[str]) -> tuple[bool, str, list[str]]: |
| 3539 | """Pull ``--store-key <NAME>`` / ``--store-key=<NAME>`` out of ``extra_argv``. |
| 3540 | |
| 3541 | Returns ``(present, name, remaining)``. ``name`` is "" when the flag has |
| 3542 | no value; ``remaining`` is every other passthrough token, so the regular |
| 3543 | allowlist check still applies to them. |
| 3544 | """ |
| 3545 | present = False |
| 3546 | name = "" |
| 3547 | remaining: list[str] = [] |
| 3548 | i = 0 |
| 3549 | while i < len(extra_argv): |
| 3550 | arg = extra_argv[i] |
| 3551 | if arg == STORE_KEY_FLAG: |
| 3552 | present = True |
| 3553 | if i + 1 < len(extra_argv) and not extra_argv[i + 1].startswith("-"): |
| 3554 | name = extra_argv[i + 1] |
| 3555 | i += 2 |
| 3556 | continue |
| 3557 | i += 1 |
| 3558 | continue |
| 3559 | if arg.startswith(STORE_KEY_FLAG + "="): |
| 3560 | present = True |
| 3561 | name = arg[len(STORE_KEY_FLAG) + 1:] |
| 3562 | i += 1 |
| 3563 | continue |
| 3564 | remaining.append(arg) |
| 3565 | i += 1 |
| 3566 | return present, name, remaining |
| 3567 | |
| 3568 | |
| 3569 | # One credential line: longer than any real token, short enough that a |
| 3570 | # misdirected stream on stdin cannot grow memory. |
| 3571 | STORE_KEY_MAX_BYTES = 64 * 1024 |
| 3572 | |
| 3573 | |
| 3574 | def _run_store_key(name: str) -> int: |
| 3575 | """``setup --store-key <NAME>``: persist one allowlisted credential from stdin. |
| 3576 | |
| 3577 | Reads exactly one line from stdin (bounded to ``STORE_KEY_MAX_BYTES``), |
| 3578 | strips whitespace, and writes it to the global ``.env`` as a 0o600 secret |
| 3579 | through ``setup_wizard.write_api_key``. An existing line for the same |
| 3580 | name is replaced, so a rejected credential can be rotated by running the |
| 3581 | command again. The value never reaches stdout or stderr: stdout carries |
| 3582 | ``NAME=****`` plus a JSON line ``{"persisted": bool, "key": NAME}``. A |
| 3583 | name outside ``env.KEYCHAIN_KEYS`` or an empty value exits 2 without |
| 3584 | echoing anything. |
| 3585 | """ |
| 3586 | from lib import setup_wizard |
| 3587 | |
| 3588 | if name not in env.KEYCHAIN_KEYS: |
| 3589 | # Do not enumerate the allowlist here: on an official-only host a |
| 3590 | # failure hint must not name the legacy credential keys. |
| 3591 | sys.stderr.write( |
| 3592 | "[last30days] setup --store-key: unknown or missing key name " |
| 3593 | "(must be a credential name the engine loads from its .env; " |
| 3594 | "see CONFIGURATION.md).\n" |
| 3595 | ) |
| 3596 | return 2 |
| 3597 | value = sys.stdin.readline(STORE_KEY_MAX_BYTES).strip() |
| 3598 | if not value: |
| 3599 | sys.stderr.write( |
| 3600 | f"[last30days] setup --store-key {name}: empty value on stdin; " |
| 3601 | "pipe the credential as a single line.\n" |
| 3602 | ) |
| 3603 | return 2 |
| 3604 | persisted = bool( |
| 3605 | setup_wizard.write_api_key(env.CONFIG_FILE, value, key_name=name, replace=True) |
| 3606 | ) |
| 3607 | print(f"{name}=****") |
| 3608 | print(json.dumps({"persisted": persisted, "key": name})) |
| 3609 | return 0 if persisted else 1 |
| 3610 | |
| 3611 | SKILL_ONLY_FLAGS = { |
| 3612 | "--agent", |
| 3613 | } |
| 3614 | |
| 3615 | # Doctor passthrough: `doctor --json` / `doctor --cached` mirror the setup |
| 3616 | # passthrough pattern (neither is a global parser flag; they only mean |
| 3617 | # something to doctor). `--cached` serves the stored doctor-cache.json report |
| 3618 | # within its TTL and falls through to a live run otherwise. |
| 3619 | DOCTOR_PASSTHROUGH_FLAGS = { |
| 3620 | "--json", |
| 3621 | "--cached", |
| 3622 | "--postmortem", |
| 3623 | "--probe", |
| 3624 | } |
| 3625 | |
| 3626 | |
| 3627 | def _looks_inline_json(value: str) -> bool: |
| 3628 | """True when a --x-posts argument is JSON text rather than a path.""" |
| 3629 | stripped = value.strip() |
| 3630 | return stripped.startswith(("{", "[")) or "\n" in value |
| 3631 | |
| 3632 | |
| 3633 | def _comparison_requested(args: argparse.Namespace, topic: str) -> bool: |
| 3634 | """Whether this invocation is a comparison run (vs-topic or competitor flags).""" |
| 3635 | from lib import planner as _planner |
| 3636 | |
| 3637 | return any( |
| 3638 | value is not None |
| 3639 | for value in (args.competitors, args.competitors_list, args.competitors_plan) |
| 3640 | ) or len(_planner._comparison_entities(topic, uncapped=True)) >= 2 |
| 3641 | |
| 3642 | |
| 3643 | PERSON_FLAGS = (("--employer", "employer"), ("--linkedin", "linkedin"), ("--email", "email")) |
| 3644 | |
| 3645 | |
| 3646 | def _person_inputs_gate(args: argparse.Namespace, topic: str) -> int | None: |
| 3647 | """Reject person flags that cannot define a person run; exit 2 or None. |
| 3648 | |
| 3649 | A person run needs a single topic: comparison runs would split the |
| 3650 | run's lookup caps across entities, so they take no person flags. |
| 3651 | Malformed values fail here, before any config probe or paid call. |
| 3652 | """ |
| 3653 | passed = [flag for flag, dest in PERSON_FLAGS if getattr(args, dest) is not None] |
| 3654 | if not passed: |
| 3655 | return None |
| 3656 | if not topic: |
| 3657 | sys.stderr.write(f"[last30days] {', '.join(passed)} requires a person topic.\n") |
| 3658 | return 2 |
| 3659 | if _comparison_requested(args, topic): |
| 3660 | sys.stderr.write( |
| 3661 | f"[last30days] {', '.join(passed)} applies to a single-person run, not a " |
| 3662 | "comparison run. Research each person separately.\n" |
| 3663 | ) |
| 3664 | return 2 |
| 3665 | try: |
| 3666 | person.build_person_context( |
| 3667 | topic, employer=args.employer, linkedin=args.linkedin, email=args.email, |
| 3668 | ) |
| 3669 | except ValueError as exc: |
| 3670 | sys.stderr.write(f"[last30days] {exc}\n") |
| 3671 | return 2 |
| 3672 | return None |
| 3673 | |
| 3674 | |
| 3675 | # Wall time for the whole person resolve step, shared by every call in it. |
| 3676 | PERSON_RESOLVE_SECONDS = 60.0 |
| 3677 | PERSON_NO_X_REASON = "person run: no X account linked from the person's LinkedIn profile or employer bio" |
| 3678 | |
| 3679 | |
| 3680 | def _resolve_person( |
| 3681 | ctx: "person.PersonContext", config: dict, requested_sources: list[str] | None, |
| 3682 | ) -> "person.PersonContext": |
| 3683 | """Run the LinkedIn resolution and the employer bio lane concurrently under |
| 3684 | one shared deadline; return the context with whatever resolved in time. |
| 3685 | |
| 3686 | Daemon threads, not an executor: a hung lane must not hold the process |
| 3687 | open past the deadline. The LinkedIn lane works on its own copy of the |
| 3688 | context, so a straggler can never write to the one the run continues with. |
| 3689 | """ |
| 3690 | import copy |
| 3691 | import queue |
| 3692 | import threading |
| 3693 | |
| 3694 | from lib import employer_site, person_linkedin |
| 3695 | |
| 3696 | deadline = time.monotonic() + PERSON_RESOLVE_SECONDS |
| 3697 | person_linkedin.anchor_supplied_url(ctx) |
| 3698 | linkedin_ctx = copy.deepcopy(ctx) |
| 3699 | results: "queue.Queue[tuple[str, object]]" = queue.Queue() |
| 3700 | run_id = uuid.uuid4().hex |
| 3701 | |
| 3702 | def _linkedin() -> None: |
| 3703 | try: |
| 3704 | value: object = person_linkedin.resolve_linkedin( |
| 3705 | linkedin_ctx, config, deadline_monotonic=deadline, run_id=run_id, |
| 3706 | requested_sources=requested_sources, |
| 3707 | ) |
| 3708 | except Exception as exc: # noqa: BLE001 - a lane failure is a status |
| 3709 | sys.stderr.write(f"[Person] LinkedIn resolution failed: {type(exc).__name__}\n") |
| 3710 | value = None |
| 3711 | results.put(("linkedin", value)) |
| 3712 | |
| 3713 | def _bio() -> None: |
| 3714 | try: |
| 3715 | value: object = employer_site.find_bio( |
| 3716 | ctx.full_name, domain=ctx.employer_domain or None, |
| 3717 | employer_name=ctx.employer_name or None, email_domain=ctx.email_domain or None, |
| 3718 | deadline_monotonic=deadline, site_search=None, |
| 3719 | ) |
| 3720 | except Exception as exc: # noqa: BLE001 - a lane failure is a status |
| 3721 | sys.stderr.write(f"[Person] Employer bio lane failed: {type(exc).__name__}\n") |
| 3722 | value = {"status": "failed", "url": "", "title": "", "bio": "", "links": [], "domain": ""} |
| 3723 | results.put(("bio", value)) |
| 3724 | |
| 3725 | for name, target in (("linkedin", _linkedin), ("bio", _bio)): |
| 3726 | threading.Thread(target=target, name=f"person-{name}", daemon=True).start() |
| 3727 | |
| 3728 | pending = {"linkedin", "bio"} |
| 3729 | resolved, bio = None, None |
| 3730 | while pending: |
| 3731 | remaining = deadline - time.monotonic() |
| 3732 | if remaining <= 0: |
| 3733 | break |
| 3734 | try: |
| 3735 | name, value = results.get(timeout=remaining) |
| 3736 | except queue.Empty: |
| 3737 | break |
| 3738 | pending.discard(name) |
| 3739 | if name == "linkedin": |
| 3740 | resolved = value |
| 3741 | else: |
| 3742 | bio = value |
| 3743 | |
| 3744 | if isinstance(resolved, person.PersonContext): |
| 3745 | ctx = resolved |
| 3746 | elif "linkedin" not in pending: |
| 3747 | ctx.set_linkedin_status(person.LINKEDIN_FAILED) |
| 3748 | if isinstance(bio, dict): |
| 3749 | ctx.bio = bio |
| 3750 | if pending: |
| 3751 | ctx.timed_out = True |
| 3752 | if "linkedin" in pending and ctx.linkedin_status is None: |
| 3753 | ctx.set_linkedin_status(person.LINKEDIN_FAILED) |
| 3754 | sys.stderr.write( |
| 3755 | f"[Person] Resolve step hit its {PERSON_RESOLVE_SECONDS:g}s deadline; " |
| 3756 | f"continuing without: {', '.join(sorted(pending))}\n" |
| 3757 | ) |
| 3758 | return ctx |
| 3759 | |
| 3760 | |
| 3761 | def _person_resolve_step( |
| 3762 | args: argparse.Namespace, topic: str, config: dict, requested_sources: list[str] | None, |
| 3763 | ) -> "person.PersonContext | None": |
| 3764 | """Build and resolve the person context; fill empty handle slots. |
| 3765 | |
| 3766 | Returns None (and changes nothing) when no person flag was passed. Mock |
| 3767 | runs build the context but make no lookups. |
| 3768 | """ |
| 3769 | ctx = person.build_person_context( |
| 3770 | topic, employer=args.employer, linkedin=args.linkedin, email=args.email, |
| 3771 | ) |
| 3772 | if ctx is None: |
| 3773 | return None |
| 3774 | if not args.mock: |
| 3775 | ctx = _resolve_person(ctx, config, requested_sources) |
| 3776 | args.x_handle, args.github_user = person.apply_derived_handles( |
| 3777 | ctx, x_handle=args.x_handle, github_user=args.github_user, |
| 3778 | ) |
| 3779 | for slot, label in (("x", "X handle"), ("github", "GitHub user")): |
| 3780 | if slot in ctx.derived_handles: |
| 3781 | sys.stderr.write(f"[Person] {label} from the person's own links: @{ctx.derived_handles[slot]}\n") |
| 3782 | if not args.x_handle and not args.no_x_handle: |
| 3783 | args.no_x_handle = PERSON_NO_X_REASON |
| 3784 | sys.stderr.write( |
| 3785 | f"[Person] LinkedIn: {ctx.linkedin_status or 'not checked'}; " |
| 3786 | f"anchors: {len(ctx.anchors)}; bio page: {(ctx.bio or {}).get('status') or 'not checked'}\n" |
| 3787 | ) |
| 3788 | return ctx |
| 3789 | |
| 3790 | |
| 3791 | LAW7_HOST_PLAN_EXIT = 2 |
| 3792 | X_HANDLE_DECISION_EXIT = 2 |
| 3793 | |
| 3794 | |
| 3795 | def _x_handle_decision_signal( |
| 3796 | args: argparse.Namespace, topic: str, external_plan: object, |
| 3797 | available_sources: list[str], |
| 3798 | ) -> str: |
| 3799 | """Agent-host marker when a hosted entity run plans X with no handle decision. |
| 3800 | |
| 3801 | An entity topic's own posts are the primary X evidence, and only a |
| 3802 | resolved handle lets X search them. On hosted runs the host model resolves |
| 3803 | handles (the engine's auto-resolve stands down for --plan), so a skipped |
| 3804 | lookup used to cost nothing and went unnoticed. Returns "" when the run |
| 3805 | is exempt or already decided (--x-handle or --no-x-handle), or when X |
| 3806 | will not run (unavailable, --search without x, or EXCLUDE_SOURCES=x). |
| 3807 | """ |
| 3808 | if external_plan is None or args.mock or args.quick: |
| 3809 | return "" |
| 3810 | if args.x_handle or args.no_x_handle: |
| 3811 | return "" |
| 3812 | if "@" in topic or _comparison_requested(args, topic): |
| 3813 | return "" |
| 3814 | if not _looks_like_entity_topic(topic): |
| 3815 | return "" |
| 3816 | if "x" not in available_sources: |
| 3817 | return "" |
| 3818 | if not pipeline._external_plan_names_source(external_plan, "x"): |
| 3819 | return "" |
| 3820 | return env.agent_host_signal() |
| 3821 | |
| 3822 | |
| 3823 | def _x_handle_decision_message(signal: str) -> str: |
| 3824 | return ( |
| 3825 | "[Resolve] X handle decision missing: this run is agent-hosted " |
| 3826 | f"({signal} is set), the topic names a person, company, or product, and " |
| 3827 | "the plan searches X, but the command has no --x-handle. Without one X " |
| 3828 | "cannot search the subject's own posts. Resolve it first " |
| 3829 | "(references/research-runbook.md Step 0.5, Section A): pass " |
| 3830 | "--official-site=<domain> so the engine reads the handle from the " |
| 3831 | "homepage links, or find it with a search restricted to x.com through " |
| 3832 | "your search tool's domain filter, then re-run with --x-handle=<handle>. " |
| 3833 | "If both came up empty, or the topic is a theme rather than an entity, " |
| 3834 | "re-run with --no-x-handle=\"<reason>\".\n" |
| 3835 | ) |
| 3836 | |
| 3837 | |
| 3838 | def _law7_host_plan_message(signal: str) -> str: |
| 3839 | return ( |
| 3840 | "[Planner] LAW 7: no --plan passed, and this run is agent-hosted " |
| 3841 | f"({signal} is set). The engine stopped before retrieval and did not " |
| 3842 | "call its internal planner. If you are the reasoning model hosting " |
| 3843 | "this skill, YOU ARE the planner; no API key or provider is needed. " |
| 3844 | "Write the JSON query plan (references/research-runbook.md Step 0.75) " |
| 3845 | "and pass it on stdin with a " |
| 3846 | "quoted heredoc: --plan - <<'PLAN_EOF' ... PLAN_EOF " |
| 3847 | "(see Research Execution in that " |
| 3848 | "runbook). With no " |
| 3849 | "web-search tool, pass --auto-resolve instead. For headless or cron " |
| 3850 | f"runs under an agent, set {env.ALLOW_ENGINE_PLAN_VAR}=1 to let the " |
| 3851 | "engine plan internally.\n" |
| 3852 | ) |
| 3853 | |
| 3854 | |
| 3855 | def _law7_host_plan_signal(args: argparse.Namespace, topic: str) -> str: |
| 3856 | """Identify a blocked agent run before configuration probes run.""" |
| 3857 | if not topic: |
| 3858 | return "" |
| 3859 | if args.plan or args.mock or args.hiring_signals or args.auto_resolve: |
| 3860 | return "" |
| 3861 | if _comparison_requested(args, topic): |
| 3862 | return "" |
| 3863 | if env.engine_plan_allowed(): |
| 3864 | return "" |
| 3865 | return env.agent_host_signal() |
| 3866 | |
| 3867 | |
| 3868 | def _law7_host_plan_gate(args: argparse.Namespace, topic: str) -> int | None: |
| 3869 | """Stop a plan-less agent research run after dispatch and cache exemptions.""" |
| 3870 | signal = _law7_host_plan_signal(args, topic) |
| 3871 | if not signal: |
| 3872 | return None |
| 3873 | sys.stderr.write(_law7_host_plan_message(signal)) |
| 3874 | return LAW7_HOST_PLAN_EXIT |
| 3875 | |
| 3876 | |
| 3877 | def _read_x_envelope( |
| 3878 | path: str, |
| 3879 | topic: str, |
| 3880 | args: argparse.Namespace, |
| 3881 | *, |
| 3882 | x_handle: str | None, |
| 3883 | x_related: list[str] | None, |
| 3884 | ) -> x_envelope.Envelope: |
| 3885 | """Validate a host-fetched X envelope against this run's window and topic.""" |
| 3886 | from_date, to_date = dates.get_date_range( |
| 3887 | args.lookback_days or 30, as_of_date=args.as_of_date |
| 3888 | ) |
| 3889 | return x_envelope.read( |
| 3890 | path, |
| 3891 | (from_date, to_date), |
| 3892 | topic, |
| 3893 | handles=[x_handle] if x_handle else [], |
| 3894 | related=[h for h in (x_related or []) if h and h.strip()], |
| 3895 | ) |
| 3896 | |
| 3897 | |
| 3898 | def _attach_entity_envelopes(comp_plan: dict[str, dict], args: argparse.Namespace) -> None: |
| 3899 | """Validate every per-entity ``x_posts`` path in a --competitors-plan. |
| 3900 | |
| 3901 | Each envelope is checked against its own entity (topic) and that entry's |
| 3902 | ``x_handle``/``x_related`` handles, and stored on the entry as |
| 3903 | ``_x_envelope`` for the entity sub-run. Raises EnvelopeContractError. |
| 3904 | """ |
| 3905 | for entry in comp_plan.values(): |
| 3906 | raw = entry.get("x_posts") |
| 3907 | if not raw: |
| 3908 | continue |
| 3909 | if not isinstance(raw, str) or _looks_inline_json(raw): |
| 3910 | raise x_envelope.EnvelopeContractError( |
| 3911 | f"--competitors-plan entry {entry.get('_name', '')!r}: x_posts must " |
| 3912 | "be a file path to a last30days-x-posts/1 envelope, never inline JSON. " |
| 3913 | "Rewrite the plan entry, or drop its x_posts field." |
| 3914 | ) |
| 3915 | related = entry.get("x_related") if isinstance(entry.get("x_related"), list) else None |
| 3916 | entry["_x_envelope"] = _read_x_envelope( |
| 3917 | raw, str(entry.get("_name") or ""), args, |
| 3918 | x_handle=entry.get("x_handle") if isinstance(entry.get("x_handle"), str) else None, |
| 3919 | x_related=[str(h) for h in related] if related else None, |
| 3920 | ) |
| 3921 | |
| 3922 | |
| 3923 | def _combine_envelope_digests(main_sha256: str | None, entity_sha256: dict[str, str]) -> str | None: |
| 3924 | """One digest binding the last-report cache to every envelope a run uses. |
| 3925 | |
| 3926 | A single top-level envelope is bound by its own file digest; per-entity |
| 3927 | comparison envelopes are folded, name-sorted, into one digest. Both the |
| 3928 | cache write (validated envelopes) and the cache lookup (planned paths) |
| 3929 | must go through here so a comparison cache can be reused. |
| 3930 | """ |
| 3931 | parts: list[str] = [] |
| 3932 | if main_sha256: |
| 3933 | parts.append(main_sha256) |
| 3934 | for name in sorted(entity_sha256): |
| 3935 | parts.append(f"{name}:{entity_sha256[name]}") |
| 3936 | if not parts: |
| 3937 | return None |
| 3938 | if len(parts) == 1 and main_sha256: |
| 3939 | return main_sha256 |
| 3940 | return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() |
| 3941 | |
| 3942 | |
| 3943 | def _x_envelope_digest( |
| 3944 | main: x_envelope.Envelope | None, comp_plan: dict[str, dict] | None |
| 3945 | ) -> str | None: |
| 3946 | """Digest of the validated envelopes this run used (cache write side).""" |
| 3947 | entity_sha256 = { |
| 3948 | name: entry["_x_envelope"].sha256 |
| 3949 | for name, entry in (comp_plan or {}).items() |
| 3950 | if entry.get("_x_envelope") is not None |
| 3951 | } |
| 3952 | return _combine_envelope_digests(main.sha256 if main is not None else None, entity_sha256) |
| 3953 | |
| 3954 | |
| 3955 | def _envelope_digest( |
| 3956 | x_main: x_envelope.Envelope | None, |
| 3957 | comp_plan: dict[str, dict] | None, |
| 3958 | reddit_threads: reddit_envelope.Envelope | None = None, |
| 3959 | shortform_urls: shortform_envelope.Envelope | None = None, |
| 3960 | ) -> str | None: |
| 3961 | """One digest binding the report cache to every host envelope of the run. |
| 3962 | |
| 3963 | Without a --reddit-threads or --shortform-urls envelope this is the X |
| 3964 | digest unchanged; with one, its file digest is folded in, so a different |
| 3965 | thread or URL list never replays a report built from another. |
| 3966 | """ |
| 3967 | x_digest = _x_envelope_digest(x_main, comp_plan) |
| 3968 | if reddit_threads is None and shortform_urls is None: |
| 3969 | return x_digest |
| 3970 | parts = [f"x:{x_digest}"] if x_digest else [] |
| 3971 | if reddit_threads is not None: |
| 3972 | parts.append(f"reddit:{reddit_threads.sha256}") |
| 3973 | if shortform_urls is not None: |
| 3974 | parts.append(f"shortform:{shortform_urls.sha256}") |
| 3975 | return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() |
| 3976 | |
| 3977 | |
| 3978 | def _validate_extra_argv(parser: argparse.ArgumentParser, topic: str, extra_argv: list[str]) -> None: |
| 3979 | if not extra_argv: |
| 3980 | return |
| 3981 | if topic.lower() == "setup": |
| 3982 | if USE_RECORDED_BROWSER_CONSENT_FLAG in extra_argv and len(extra_argv) > 1: |
| 3983 | parser.error(f"{USE_RECORDED_BROWSER_CONSENT_FLAG} must be the only setup option") |
| 3984 | # --store-key and --install-hooks/--uninstall-hooks carry optional |
| 3985 | # value tokens validated later by their handlers, not here. |
| 3986 | _, _, extra_argv = _split_store_key(extra_argv) |
| 3987 | _, _, extra_argv = _split_hook_flags(extra_argv) |
| 3988 | unsupported = [arg for arg in extra_argv if arg not in SETUP_PASSTHROUGH_FLAGS] |
| 3989 | if unsupported: |
| 3990 | parser.error( |
| 3991 | "unsupported setup argument(s): " |
| 3992 | + ", ".join(unsupported) |
| 3993 | + f"; supported setup passthrough flags are {', '.join(sorted(SETUP_PASSTHROUGH_FLAGS))}" |
| 3994 | ) |
| 3995 | return |
| 3996 | if topic.lower() == "doctor": |
| 3997 | unsupported = [arg for arg in extra_argv if arg not in DOCTOR_PASSTHROUGH_FLAGS] |
| 3998 | if unsupported: |
| 3999 | parser.error( |
| 4000 | "unsupported doctor argument(s): " |
| 4001 | + ", ".join(unsupported) |
| 4002 | + f"; supported doctor passthrough flags are {', '.join(sorted(DOCTOR_PASSTHROUGH_FLAGS))}" |
| 4003 | ) |
| 4004 | return |
| 4005 | skill_only = [arg for arg in extra_argv if arg in SKILL_ONLY_FLAGS] |
| 4006 | other_unknown = [arg for arg in extra_argv if arg not in SKILL_ONLY_FLAGS] |
| 4007 | if skill_only: |
| 4008 | message = ( |
| 4009 | "unsupported Python CLI argument(s): " |
| 4010 | + ", ".join(skill_only) |
| 4011 | + "; these are skill arguments and must not be forwarded to scripts/last30days.py" |
| 4012 | ) |
| 4013 | if other_unknown: |
| 4014 | message += "; also unsupported: " + ", ".join(other_unknown) |
| 4015 | parser.error(message) |
| 4016 | parser.error("unsupported Python CLI argument(s): " + ", ".join(extra_argv)) |
| 4017 | |
| 4018 | |
| 4019 | def _has_invalid_cli_combination(args: argparse.Namespace, topic: str) -> bool: |
| 4020 | """True when parsed research flags are guaranteed to exit 2 before retrieval.""" |
| 4021 | if args.discover is not None: |
| 4022 | return bool( |
| 4023 | topic |
| 4024 | or args.drill |
| 4025 | or args.as_of_date |
| 4026 | or args.emit == "html" |
| 4027 | or args.publish_html |
| 4028 | or args.deep_research |
| 4029 | or (args.nominate_only and (args.judgments is not None or args.finalize)) |
| 4030 | or (args.judgments is not None and args.finalize) |
| 4031 | or (args.angles is not None and not args.finalize) |
| 4032 | ) |
| 4033 | if ( |
| 4034 | args.discover_shallow |
| 4035 | or args.nominate_only |
| 4036 | or args.judgments is not None |
| 4037 | or args.finalize |
| 4038 | or args.angles is not None |
| 4039 | ): |
| 4040 | return True |
| 4041 | if args.drill: |
| 4042 | return bool(topic or args.deep_research or (args.publish_html and args.emit != "html")) |
| 4043 | if args.deep_research and (not topic or _comparison_requested(args, topic)): |
| 4044 | return True |
| 4045 | if not topic: |
| 4046 | return True |
| 4047 | if (args.clarify_angle is not None or args.clarify_broadly) and not _will_tentatively_use_hosted_api(args, topic): |
| 4048 | return True |
| 4049 | if args.publish_html and args.emit != "html": |
| 4050 | return True |
| 4051 | return False |
| 4052 | |
| 4053 | |
| 4054 | def _will_tentatively_use_hosted_api(args: argparse.Namespace, topic: str) -> bool: |
| 4055 | """True when process env and CLI flags may route a research topic to the hosted backend. |
| 4056 | |
| 4057 | Corpus flags/env vars do not disqualify hosted mode here because |
| 4058 | ``EXCLUDE_SOURCES=corpus`` in ``.env`` can disable the corpus and keep the |
| 4059 | run hosted. Local fallback reloads full config once ``uses_hosted_api`` is |
| 4060 | confirmed False. |
| 4061 | """ |
| 4062 | if not topic or not env.hosted_backend_configured(): |
| 4063 | return False |
| 4064 | if ( |
| 4065 | args.cached_report |
| 4066 | or args.mock |
| 4067 | or args.record_fixtures |
| 4068 | or args.deep_research |
| 4069 | or args.discover is not None |
| 4070 | or args.drill |
| 4071 | ): |
| 4072 | return False |
| 4073 | if args.perplexity_search_type is not None and env.read_secret_env("PERPLEXITY_API_KEY"): |
| 4074 | return False |
| 4075 | return True |
| 4076 | |
| 4077 | |
| 4078 | def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: list[str]) -> env.ConfigLoadPolicy: |
| 4079 | normalized_topic = "" if args.research_only or args.cached_report else topic.lower() |
| 4080 | reuse_browser_consent = normalized_topic == "setup" and USE_RECORDED_BROWSER_CONSENT_FLAG in extra_argv |
| 4081 | is_library_command = _is_library_command(normalized_topic) |
| 4082 | # Queue commands are local SQLite reads/writes: like library commands they |
| 4083 | # must never trigger browser-cookie extraction or Keychain prompts. |
| 4084 | is_queue_command = _is_queue_command(normalized_topic) |
| 4085 | is_cached_verification = ( |
| 4086 | bool(getattr(args, "verify_freshness", None)) |
| 4087 | and not topic |
| 4088 | and not args.drill |
| 4089 | and args.discover is None |
| 4090 | ) |
| 4091 | is_inspection = bool(args.diagnose or args.preflight or normalized_topic == "doctor") |
| 4092 | is_invalid = _has_invalid_cli_combination(args, topic) |
| 4093 | tentative_hosted = _will_tentatively_use_hosted_api(args, topic) |
| 4094 | law7_blocked = bool(_law7_host_plan_signal(args, topic)) |
| 4095 | if args.no_browser_cookies: |
| 4096 | browser_mode = "off" |
| 4097 | elif ( |
| 4098 | is_inspection or args.cached_report |
| 4099 | or is_library_command or is_queue_command or is_cached_verification |
| 4100 | ): |
| 4101 | # doctor is plan-only like --diagnose: it must never read cookies. |
| 4102 | # Cache-only freshness verification hits only point APIs (Polymarket, |
| 4103 | # GitHub, StockTwits) - no cookie-backed source, so no Keychain prompt. |
| 4104 | browser_mode = "plan_only" |
| 4105 | elif normalized_topic == "setup": |
| 4106 | browser_mode = ( |
| 4107 | "read" |
| 4108 | if not _setup_is_non_auto(extra_argv) |
| 4109 | and (reuse_browser_consent or _setup_has_fresh_browser_consent(args, extra_argv)) |
| 4110 | else "off" |
| 4111 | ) |
| 4112 | elif ( |
| 4113 | args.mock |
| 4114 | or args.finalize |
| 4115 | or is_invalid |
| 4116 | or tentative_hosted |
| 4117 | ): |
| 4118 | # Mock runs, offline discovery finalize, empty/invalid invocations, and |
| 4119 | # tentative hosted-API runs never read local browser cookies. |
| 4120 | browser_mode = "off" |
| 4121 | elif law7_blocked: |
| 4122 | # Hosted and cached paths need config before dispatch, but no browser read. |
| 4123 | browser_mode = "plan_only" |
| 4124 | else: |
| 4125 | browser_mode = "read" |
| 4126 | |
| 4127 | # Skip Keychain / pass app-credential lookups on modes that do not need |
| 4128 | # local provider keys (mock, offline, cached, library, queue, invalid, or |
| 4129 | # hosted API runs). Hosted runs that fall back locally reload with stores on. |
| 4130 | if args.mock: |
| 4131 | load_secret_stores = False |
| 4132 | elif is_inspection: |
| 4133 | load_secret_stores = True |
| 4134 | elif ( |
| 4135 | args.cached_report |
| 4136 | or is_library_command |
| 4137 | or is_queue_command |
| 4138 | or is_cached_verification |
| 4139 | ): |
| 4140 | load_secret_stores = False |
| 4141 | elif normalized_topic == "setup": |
| 4142 | load_secret_stores = not _setup_skips_secret_stores(extra_argv) |
| 4143 | elif ( |
| 4144 | args.finalize |
| 4145 | or is_invalid |
| 4146 | or (tentative_hosted and args.perplexity_search_type is None) |
| 4147 | ): |
| 4148 | load_secret_stores = False |
| 4149 | elif law7_blocked and not (args.emit == "html" and args.synthesis_file and not args.deep_research): |
| 4150 | load_secret_stores = False |
| 4151 | else: |
| 4152 | load_secret_stores = True |
| 4153 | |
| 4154 | return env.ConfigLoadPolicy( |
| 4155 | browser_cookies=browser_mode, |
| 4156 | inspect_ignored_project_config=is_inspection, |
| 4157 | require_recorded_browser_consent=reuse_browser_consent, |
| 4158 | load_secret_stores=load_secret_stores, |
| 4159 | ) |
| 4160 | |
| 4161 | |
| 4162 | def _preflight_has_perplexity_key_for_research( |
| 4163 | args: argparse.Namespace, |
| 4164 | topic: str, |
| 4165 | extra_argv: list[str], |
| 4166 | config: dict[str, Any], |
| 4167 | ) -> bool: |
| 4168 | """Whether a real research run with ``args`` would see a direct PERPLEXITY_API_KEY. |
| 4169 | |
| 4170 | ``--preflight`` inspects with ``load_secret_stores=True``, whereas a real |
| 4171 | research run on an agent host without ``--plan`` skips Keychain/``pass`` |
| 4172 | before hosted dispatch. |
| 4173 | """ |
| 4174 | if not config.get("PERPLEXITY_API_KEY"): |
| 4175 | return False |
| 4176 | research_args = argparse.Namespace(**vars(args)) |
| 4177 | research_args.preflight = False |
| 4178 | research_args.diagnose = False |
| 4179 | research_policy = _config_policy_for_args( |
| 4180 | research_args, topic or "preflight", extra_argv |
| 4181 | ) |
| 4182 | if research_policy.load_secret_stores: |
| 4183 | return True |
| 4184 | no_store_policy = env.ConfigLoadPolicy( |
| 4185 | browser_cookies="off", |
| 4186 | allow_project_config=research_policy.allow_project_config, |
| 4187 | inspect_ignored_project_config=False, |
| 4188 | load_secret_stores=False, |
| 4189 | ) |
| 4190 | return bool(env.get_config(policy=no_store_policy).get("PERPLEXITY_API_KEY")) |
| 4191 | |
| 4192 | |
| 4193 | def _run_library_feed(args: argparse.Namespace, config: dict[str, object]) -> int: |
| 4194 | """Generate the local research index/feed and optionally publish it.""" |
| 4195 | from lib import feed, html_publish, library |
| 4196 | |
| 4197 | if args.publish_html: |
| 4198 | sys.stderr.write( |
| 4199 | "[last30days] library feed uses --publish, not --publish-html.\n" |
| 4200 | ) |
| 4201 | return 2 |
| 4202 | if args.output: |
| 4203 | sys.stderr.write( |
| 4204 | "[last30days] library feed writes index.html and feed.xml to --save-dir; " |
| 4205 | "--output is not supported.\n" |
| 4206 | ) |
| 4207 | return 2 |
| 4208 | |
| 4209 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 4210 | if save_dir_exit is not None: |
| 4211 | return save_dir_exit |
| 4212 | scoped = _is_scoped_save_dir(args.save_dir) |
| 4213 | memory_dir = Path(args.save_dir).expanduser() if args.save_dir else library.DEFAULT_MEMORY_DIR |
| 4214 | output_dir = memory_dir.resolve() |
| 4215 | # Scoped libraries (--save-dir) must not mix in the global briefing |
| 4216 | # archive: a client-specific or publishable feed pulling unrelated default |
| 4217 | # briefings could publish them publicly. The default library keeps the |
| 4218 | # archive; a scoped one reads only its own directory. |
| 4219 | briefs_dir = ( |
| 4220 | memory_dir / "briefings" if scoped else library.DEFAULT_BRIEFS_DIR |
| 4221 | ) |
| 4222 | entries, notes = library.scan_library(memory_dir, briefs_dir) |
| 4223 | feed_author = str( |
| 4224 | config.get("LAST30DAYS_LIBRARY_OWNER") or "last30days research library" |
| 4225 | ) |
| 4226 | output_dir.mkdir(parents=True, exist_ok=True) |
| 4227 | library_id = library.get_or_create_library_id(output_dir) |
| 4228 | rendered_briefs_dir = output_dir / "briefs" |
| 4229 | private_entries = { |
| 4230 | entry.entry_id for entry in entries if library.public_markdown(entry.content) != entry.content |
| 4231 | } |
| 4232 | _ensure_output_directory(rendered_briefs_dir, private=bool(private_entries)) |
| 4233 | |
| 4234 | def _preserve_hand_written_page(existing_path: Path, generated_marker: str) -> None: |
| 4235 | """Back up any page library feed did not generate before overwriting it.""" |
| 4236 | if not existing_path.exists(): |
| 4237 | return |
| 4238 | try: |
| 4239 | marker_found = generated_marker in existing_path.read_text(encoding="utf-8") |
| 4240 | except (OSError, UnicodeDecodeError): |
| 4241 | marker_found = False |
| 4242 | if marker_found: |
| 4243 | return |
| 4244 | backup = existing_path.with_suffix(existing_path.suffix + ".bak") |
| 4245 | counter = 1 |
| 4246 | while backup.exists(): |
| 4247 | backup = existing_path.with_suffix(f"{existing_path.suffix}.bak{counter}") |
| 4248 | counter += 1 |
| 4249 | existing_path.replace(backup) |
| 4250 | sys.stderr.write( |
| 4251 | f"[last30days] {existing_path.name} was not generated by " |
| 4252 | f"library feed; preserved the original at {backup.name}\n" |
| 4253 | ) |
| 4254 | |
| 4255 | publishable_entries: list[library.LibraryEntry] = [] |
| 4256 | publishable_brief_documents: dict[str, str] = {} |
| 4257 | omitted_private_briefs = 0 |
| 4258 | for entry in entries: |
| 4259 | rendered = html_render.render_library_brief(entry) |
| 4260 | target = rendered_briefs_dir / entry.output_name |
| 4261 | _preserve_hand_written_page(target, html_render.LIBRARY_BRIEF_MARKER) |
| 4262 | save_rendered_output( |
| 4263 | rendered, |
| 4264 | str(target), |
| 4265 | private=entry.entry_id in private_entries, |
| 4266 | ) |
| 4267 | if library.is_unbounded_private_brief(entry.content, source_format=entry.source_format): |
| 4268 | omitted_private_briefs += 1 |
| 4269 | continue |
| 4270 | publishable_entries.append(entry) |
| 4271 | publishable_brief_documents[entry.entry_id] = html_render.render_library_brief( |
| 4272 | entry, include_private=False |
| 4273 | ) |
| 4274 | |
| 4275 | current_brief_names = {entry.output_name for entry in entries} |
| 4276 | for path in rendered_briefs_dir.glob("*.html"): |
| 4277 | is_orphan = path.name not in current_brief_names |
| 4278 | if not (is_orphan and library.is_generated_brief_name(path.name)): |
| 4279 | continue |
| 4280 | # A generated-looking name is not proof of ownership; only prune |
| 4281 | # pages that carry the renderer's own marker. |
| 4282 | try: |
| 4283 | generated = html_render.LIBRARY_BRIEF_MARKER in path.read_text( |
| 4284 | encoding="utf-8" |
| 4285 | ) |
| 4286 | except (OSError, UnicodeDecodeError): |
| 4287 | generated = False |
| 4288 | if generated: |
| 4289 | path.unlink() |
| 4290 | |
| 4291 | feed_xml = feed.render_atom(entries, library_id=library_id, author=feed_author) |
| 4292 | index_html = html_render.render_library_index(entries) |
| 4293 | feed_path = output_dir / "feed.xml" |
| 4294 | index_path = output_dir / "index.html" |
| 4295 | _preserve_hand_written_page(feed_path, "urn:last30days:research-library") |
| 4296 | _preserve_hand_written_page( |
| 4297 | index_path, "Generated locally by <strong>last30days</strong>" |
| 4298 | ) |
| 4299 | feed_path.write_text(feed_xml, encoding="utf-8") |
| 4300 | index_path.write_text(index_html, encoding="utf-8") |
| 4301 | |
| 4302 | for note in notes: |
| 4303 | sys.stderr.write(f"[last30days] Library note: {note}\n") |
| 4304 | sys.stderr.write( |
| 4305 | f"[last30days] Library feed generated {len(entries)} brief(s): " |
| 4306 | f"{index_path} and {feed_path}\n" |
| 4307 | ) |
| 4308 | |
| 4309 | if args.publish: |
| 4310 | if omitted_private_briefs: |
| 4311 | sys.stderr.write( |
| 4312 | f"[last30days] Omitted {omitted_private_briefs} private local-corpus " |
| 4313 | "finished brief(s) from public publishing.\n" |
| 4314 | ) |
| 4315 | password = _publish_password_for_args(args, config) |
| 4316 | entry_urls: dict[str, str] = {} |
| 4317 | try: |
| 4318 | brief_results = html_publish.publish_html_documents( |
| 4319 | publishable_brief_documents, |
| 4320 | password=password, |
| 4321 | ) |
| 4322 | entry_urls = { |
| 4323 | entry_id: str(result["url"]) |
| 4324 | for entry_id, result in brief_results.items() |
| 4325 | } |
| 4326 | if batch_error := getattr(brief_results, "error", None): |
| 4327 | raise batch_error |
| 4328 | published_index = html_render.render_library_index( |
| 4329 | publishable_entries, |
| 4330 | entry_urls=entry_urls, |
| 4331 | feed_url=None, |
| 4332 | ) |
| 4333 | index_result = html_publish.publish_html(published_index, password=password) |
| 4334 | index_url = str(index_result["url"]) |
| 4335 | except (html_publish.HtmlPublishError, KeyError, OSError) as exc: |
| 4336 | sys.stderr.write(f"[last30days] Library publish failed: {exc}\n") |
| 4337 | if entry_urls: |
| 4338 | sys.stderr.write( |
| 4339 | f"[last30days] Partial publish: {len(entry_urls)} public brief " |
| 4340 | "page(s) were created before the failure.\n" |
| 4341 | ) |
| 4342 | return 1 |
| 4343 | |
| 4344 | # Keep the local artifacts useful as a record of the live publication. |
| 4345 | feed_path.write_text( |
| 4346 | feed.render_atom( |
| 4347 | publishable_entries, |
| 4348 | library_id=library_id, |
| 4349 | entry_urls=entry_urls, |
| 4350 | author=feed_author, |
| 4351 | ), |
| 4352 | encoding="utf-8", |
| 4353 | ) |
| 4354 | index_path.write_text( |
| 4355 | html_render.render_library_index(publishable_entries, entry_urls=entry_urls), |
| 4356 | encoding="utf-8", |
| 4357 | ) |
| 4358 | sys.stderr.write(f"[last30days] Published library to {index_url}\n") |
| 4359 | sys.stderr.write(f"[last30days] Local Atom feed: {feed_path}\n") |
| 4360 | print( |
| 4361 | f"Library: {index_url}\nFeed: {feed_path}\n" |
| 4362 | "Atom feed is local; host feed.xml on any static host (for example, GitHub Pages) " |
| 4363 | "to make it subscribable." |
| 4364 | ) |
| 4365 | return 0 |
| 4366 | |
| 4367 | print( |
| 4368 | f"Library: {index_path}\nFeed: {feed_path}\n" |
| 4369 | "Atom feed is local; host feed.xml on any static host (for example, GitHub Pages) " |
| 4370 | "to make it subscribable." |
| 4371 | ) |
| 4372 | return 0 |
| 4373 | |
| 4374 | |
| 4375 | def _run_library_search( |
| 4376 | args: argparse.Namespace, |
| 4377 | config: dict[str, object], |
| 4378 | query: str, |
| 4379 | ) -> int: |
| 4380 | """Search saved briefs and store sightings without network access.""" |
| 4381 | from lib import library, library_index |
| 4382 | |
| 4383 | if not query.strip(): |
| 4384 | sys.stderr.write("[last30days] library search requires a non-empty query.\n") |
| 4385 | return 2 |
| 4386 | if args.publish or args.publish_html: |
| 4387 | sys.stderr.write("[last30days] library search does not publish output.\n") |
| 4388 | return 2 |
| 4389 | if args.emit != "compact": |
| 4390 | sys.stderr.write("[last30days] library search currently supports text output only.\n") |
| 4391 | return 2 |
| 4392 | if args.output: |
| 4393 | sys.stderr.write( |
| 4394 | "[last30days] library search prints to stdout; --output is not supported.\n" |
| 4395 | ) |
| 4396 | return 2 |
| 4397 | |
| 4398 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 4399 | if save_dir_exit is not None: |
| 4400 | return save_dir_exit |
| 4401 | scoped = _is_scoped_save_dir(args.save_dir) |
| 4402 | memory_dir = Path(args.save_dir).expanduser() if args.save_dir else library.DEFAULT_MEMORY_DIR |
| 4403 | store_db = ( |
| 4404 | pipeline.scoped_store_db_path(args.save_dir) |
| 4405 | or library_index.DEFAULT_STORE_DB |
| 4406 | ) |
| 4407 | try: |
| 4408 | matches, synced = library_index.sync_and_search( |
| 4409 | query, |
| 4410 | memory_dir=memory_dir, |
| 4411 | briefs_dir=( |
| 4412 | memory_dir / "briefings" if scoped else library.DEFAULT_BRIEFS_DIR |
| 4413 | ), |
| 4414 | db_path=( |
| 4415 | memory_dir.resolve() / ".last30days-library.db" |
| 4416 | if scoped else library_index.DEFAULT_LIBRARY_DB |
| 4417 | ), |
| 4418 | # A scoped search must never merge in the shared store: one |
| 4419 | # client's sightings would leak into another client's scope. A |
| 4420 | # scoped store is read only if it exists inside the save dir. |
| 4421 | store_db_path=store_db, |
| 4422 | ) |
| 4423 | except library_index.LibrarySearchUnavailable as exc: |
| 4424 | sys.stderr.write(f"[last30days] Library search unavailable: {exc}.\n") |
| 4425 | return 2 |
| 4426 | except (OSError, sqlite3.DatabaseError) as exc: |
| 4427 | sys.stderr.write(f"[last30days] Library search failed: {exc}.\n") |
| 4428 | return 1 |
| 4429 | for note in synced.notes: |
| 4430 | sys.stderr.write(f"[last30days] Library note: {note}\n") |
| 4431 | if synced.rebuilt: |
| 4432 | sys.stderr.write("[last30days] Rebuilt a corrupt library search index.\n") |
| 4433 | print(render.render_library_search(query, matches), end="") |
| 4434 | return 0 |
| 4435 | |
| 4436 | |
| 4437 | def _run_library_harvest( |
| 4438 | args: argparse.Namespace, |
| 4439 | config: dict[str, object], |
| 4440 | ) -> int: |
| 4441 | """Scan local agent transcripts offline and archive finished briefs.""" |
| 4442 | from lib import brief_capture, library, library_index, transcript_harvest |
| 4443 | |
| 4444 | if args.publish or args.publish_html: |
| 4445 | sys.stderr.write("[last30days] library harvest does not publish output.\n") |
| 4446 | return 2 |
| 4447 | if args.output: |
| 4448 | sys.stderr.write( |
| 4449 | "[last30days] library harvest writes into <save_dir>/finished/; " |
| 4450 | "--output is not supported.\n" |
| 4451 | ) |
| 4452 | return 2 |
| 4453 | |
| 4454 | since_date = None |
| 4455 | if args.harvest_since is not None: |
| 4456 | try: |
| 4457 | since_date = datetime.date.fromisoformat(args.harvest_since.strip()) |
| 4458 | except ValueError: |
| 4459 | sys.stderr.write( |
| 4460 | f"[last30days] invalid --since date '{args.harvest_since}'; expected YYYY-MM-DD.\n" |
| 4461 | ) |
| 4462 | return 2 |
| 4463 | |
| 4464 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 4465 | if save_dir_exit is not None: |
| 4466 | return save_dir_exit |
| 4467 | if args.save_dir == "": |
| 4468 | sys.stderr.write( |
| 4469 | "[last30days] saving is disabled (--save-dir / LAST30DAYS_MEMORY_DIR is empty); " |
| 4470 | "pass --save-dir <dir> to run library harvest.\n" |
| 4471 | ) |
| 4472 | return 2 |
| 4473 | memory_dir = Path(args.save_dir).expanduser() if args.save_dir else library.DEFAULT_MEMORY_DIR |
| 4474 | |
| 4475 | try: |
| 4476 | result = transcript_harvest.harvest_transcripts( |
| 4477 | save_dir=memory_dir, |
| 4478 | source=args.harvest_source or "auto", |
| 4479 | since=since_date, |
| 4480 | dry_run=bool(args.dry_run), |
| 4481 | ) |
| 4482 | except ValueError as exc: |
| 4483 | sys.stderr.write(f"[last30days] {exc}\n") |
| 4484 | return 2 |
| 4485 | |
| 4486 | if not args.dry_run and result.saved > 0: |
| 4487 | try: |
| 4488 | save_root = memory_dir.resolve() |
| 4489 | db_path = library_index.saved_report_index_path(save_root) |
| 4490 | if not _is_scoped_save_dir(save_root): |
| 4491 | library_index.sync_library(save_root) |
| 4492 | else: |
| 4493 | library_index.sync_library(save_root, save_root / "briefings", db_path=db_path) |
| 4494 | except (library_index.LibrarySearchUnavailable, OSError, sqlite3.DatabaseError): |
| 4495 | pass |
| 4496 | |
| 4497 | for note in result.notes: |
| 4498 | sys.stderr.write(f"[last30days] Harvest note: {note}\n") |
| 4499 | |
| 4500 | finished_dir = memory_dir.resolve() / brief_capture.FINISHED_SUBDIR |
| 4501 | saved_label = "Would save" if result.dry_run else "Saved" |
| 4502 | print( |
| 4503 | f"Scanned files: {result.scanned_files}\n" |
| 4504 | f"Matched briefs: {result.matched_briefs}\n" |
| 4505 | f"{saved_label}: {result.saved}\n" |
| 4506 | f"Duplicates: {result.duplicates}\n" |
| 4507 | f"Destination: {finished_dir}" |
| 4508 | ) |
| 4509 | return 0 |
| 4510 | |
| 4511 | |
| 4512 | def _looks_like_entity_topic(topic: str) -> bool: |
| 4513 | """Whether a topic names a person, company, or product rather than a theme. |
| 4514 | |
| 4515 | Keys on brevity, not capitalization. People type lowercase: "bentgo", |
| 4516 | "peter steinberger" and "getenergy.com" are entity searches every bit as |
| 4517 | much as their title-cased forms, and requiring a capital meant the most |
| 4518 | common real-world spelling never resolved a handle. |
| 4519 | |
| 4520 | A short topic is an entity search; a longer one is a theme. "Peter |
| 4521 | Steinberger", "bentgo" and "getenergy.com" qualify; "best AI coding tools |
| 4522 | 2026" and "how to build agents that scale" do not. Question-shaped topics |
| 4523 | are themes regardless of length. |
| 4524 | |
| 4525 | Used only to decide whether resolving an X handle is worth one web search, |
| 4526 | so a false negative costs the old behavior and a false positive costs a |
| 4527 | single search. |
| 4528 | """ |
| 4529 | text = (topic or "").strip() |
| 4530 | if not text or text.endswith("?"): |
| 4531 | return False |
| 4532 | words = [w for w in re.findall(r"[A-Za-z0-9_.@'-]+", text) if w] |
| 4533 | if not words or len(words) > 4: |
| 4534 | return False |
| 4535 | if any(w.startswith("@") for w in words): |
| 4536 | return True |
| 4537 | # A theme reads as a phrase built from common words; an entity does not. |
| 4538 | common = { |
| 4539 | "best", "top", "how", "why", "what", "when", "vs", "versus", "guide", |
| 4540 | "tips", "review", "reviews", "news", "latest", "update", "updates", |
| 4541 | "trends", "tools", "and", "or", "for", "the", "with", "about", |
| 4542 | } |
| 4543 | return not any(w.lower() in common for w in words) |
| 4544 | |
| 4545 | |
| 4546 | def main() -> int: |
| 4547 | command_started = time.monotonic() |
| 4548 | # Windows: Printing Press CLIs install off PATH; resolve them before any gate runs (#1434). |
| 4549 | health.add_managed_bin_dir_to_path() |
| 4550 | parser = build_parser() |
| 4551 | # Use parse_known_args so setup sub-flags (--device-auth, --github, |
| 4552 | # --openclaw) pass through without argparse hard-exiting. |
| 4553 | args, extra_argv = parser.parse_known_args() |
| 4554 | if args.as_of_date and dates.is_today(args.as_of_date): |
| 4555 | # Naming today is a live run: every lane takes its live path. |
| 4556 | args.as_of_date = None |
| 4557 | option_argv = sys.argv[1:sys.argv.index("--")] if "--" in sys.argv else sys.argv[1:] |
| 4558 | option_tokens = {token.split("=", 1)[0] for token in option_argv} |
| 4559 | args._explicit_options = { |
| 4560 | action.dest for action in parser._actions |
| 4561 | if any(option in option_tokens for option in action.option_strings) |
| 4562 | } |
| 4563 | if args.no_research_persistence: |
| 4564 | if ( |
| 4565 | not args.research_only or not args.topic or args.discover is not None |
| 4566 | or args.drill or args.cached_report or args.synthesis_file |
| 4567 | or args.output or args.publish_html or args.record_fixtures |
| 4568 | ): |
| 4569 | parser.error("--no-research-persistence requires --research-only and a topic without output or cache modes") |
| 4570 | args.save_dir = "" |
| 4571 | if args.record_fixtures and (args.diagnose or args.preflight): |
| 4572 | # Reject before recording_requests() starts so read-only inspection |
| 4573 | # never creates or truncates a fixture file on exit. |
| 4574 | flag = "--preflight" if args.preflight else "--diagnose" |
| 4575 | sys.stderr.write(f"[last30days] --record-fixtures cannot be combined with {flag}.\n") |
| 4576 | return 2 |
| 4577 | try: |
| 4578 | if args.record_fixtures: |
| 4579 | with http.recording_requests(Path(args.record_fixtures)): |
| 4580 | return _main(parser, args, extra_argv, command_started=command_started) |
| 4581 | return _main(parser, args, extra_argv, command_started=command_started) |
| 4582 | finally: |
| 4583 | _report_proxy_session() |
| 4584 | |
| 4585 | |
| 4586 | def _report_proxy_session() -> None: |
| 4587 | """One stderr line with what the API-key proxy charged this run, if used.""" |
| 4588 | session = proxy.session_id() |
| 4589 | if session: |
| 4590 | calls, credits = proxy.session_summary() |
| 4591 | sys.stderr.write( |
| 4592 | f"[last30days] API key session {session}: {proxy.format_credits(credits)} " |
| 4593 | f"credits across {calls} paid call{'' if calls == 1 else 's'}\n" |
| 4594 | ) |
| 4595 | sys.stderr.flush() |
| 4596 | |
| 4597 | |
| 4598 | def _quality_research_results(report, diag, yt_fetch_stats): |
| 4599 | youtube_items = report.items_by_source.get("youtube") or [] |
| 4600 | instagram_items = report.items_by_source.get("instagram") or [] |
| 4601 | x_outcome = report.source_status.get("x") |
| 4602 | x_degraded_error = None |
| 4603 | if ( |
| 4604 | report.items_by_source.get("x") |
| 4605 | and x_outcome is not None |
| 4606 | and x_outcome.detail |
| 4607 | and x_outcome.detail.startswith("X served via ") |
| 4608 | and " after xai:" in x_outcome.detail |
| 4609 | ): |
| 4610 | x_degraded_error = x_outcome.detail |
| 4611 | return { |
| 4612 | "active_sources": diag.get("available_sources") or [], |
| 4613 | "youtube_videos_count": len(youtube_items), |
| 4614 | "youtube_transcripts_count": sum( |
| 4615 | 1 for it in youtube_items |
| 4616 | if (it.metadata.get("transcript_highlights") or it.metadata.get("transcript_snippet")) |
| 4617 | ), |
| 4618 | "youtube_error": report.errors_by_source.get("youtube"), |
| 4619 | "instagram_error": report.errors_by_source.get("instagram"), |
| 4620 | "x_error": report.errors_by_source.get("x"), |
| 4621 | "x_degraded_error": x_degraded_error, |
| 4622 | "youtube_captions_disabled_count": sum( |
| 4623 | 1 for it in youtube_items if it.metadata.get("captions_disabled") |
| 4624 | ), |
| 4625 | "youtube_transcript_fetch_attempts": yt_fetch_stats["attempts"], |
| 4626 | "youtube_transcript_fetch_failures": yt_fetch_stats["failures"], |
| 4627 | "youtube_transcript_target": yt_fetch_stats.get("target", 0), |
| 4628 | "youtube_bot_checked": yt_fetch_stats.get("blocked", 0), |
| 4629 | "youtube_sc_rescued": yt_fetch_stats.get("sc_rescued", 0), |
| 4630 | "instagram_items_count": len(instagram_items), |
| 4631 | } |
| 4632 | |
| 4633 | |
| 4634 | def _unsupported_hosted_options(args: argparse.Namespace) -> list[str]: |
| 4635 | explicit_options = getattr(args, "_explicit_options", ()) |
| 4636 | options = ( |
| 4637 | ("--days/--lookback-days", args.lookback_days is not None), |
| 4638 | ("--as-of", args.as_of_date is not None or "as_of_date" in explicit_options), |
| 4639 | ("--plan", args.plan is not None), |
| 4640 | ("--auto-resolve", args.auto_resolve), |
| 4641 | ("--official-site", args.official_site is not None), |
| 4642 | ("--x-handle", args.x_handle is not None), |
| 4643 | ("--no-x-handle", args.no_x_handle is not None), |
| 4644 | ("--x-related", args.x_related is not None), |
| 4645 | ("--search", args.search is not None), |
| 4646 | ("--web-backend", args.web_backend != "auto"), |
| 4647 | ("--hiring-signals", args.hiring_signals), |
| 4648 | ("--company", args.company is not None), |
| 4649 | ("--ticker", args.ticker is not None), |
| 4650 | ("--jobs-board", args.jobs_board is not None), |
| 4651 | ("--subreddits", args.subreddits is not None), |
| 4652 | ("--dedicated-subreddits", args.dedicated_subreddits is not None), |
| 4653 | ("--devto-tags", args.devto_tags is not None), |
| 4654 | ("--tiktok-hashtags", args.tiktok_hashtags is not None), |
| 4655 | ("--tiktok-creators", args.tiktok_creators is not None), |
| 4656 | ("--ig-creators", args.ig_creators is not None), |
| 4657 | ("--github-user", args.github_user is not None), |
| 4658 | ("--github-repo", args.github_repo is not None), |
| 4659 | ("--employer", args.employer is not None), |
| 4660 | ("--linkedin", args.linkedin is not None), |
| 4661 | ("--email", args.email is not None), |
| 4662 | ("--trustpilot-domain", args.trustpilot_domain is not None), |
| 4663 | ("--amazon-query", args.amazon_query is not None), |
| 4664 | ("--meta-ads-page", args.meta_ads_page is not None), |
| 4665 | ("--telegram-sources", args.telegram_sources is not None), |
| 4666 | ("--polymarket-keywords", args.polymarket_keywords is not None), |
| 4667 | ("--competitors", args.competitors is not None), |
| 4668 | ("--competitors-list", args.competitors_list is not None), |
| 4669 | ("--competitors-plan", args.competitors_plan is not None), |
| 4670 | ("--max-results", args.max_results is not None), |
| 4671 | ("--max-per-source", args.max_per_source is not None), |
| 4672 | ("--max-source-fetches", args.max_source_fetches is not None), |
| 4673 | ("--corpus-all-time", args.corpus_all_time), |
| 4674 | ("--store", args.store), |
| 4675 | ("--output", args.output is not None), |
| 4676 | ("--synthesis-file", args.synthesis_file is not None), |
| 4677 | ("--publish-html", args.publish_html), |
| 4678 | (f"--emit={args.emit}", args.emit not in {"compact", "md", "json"}), |
| 4679 | ) |
| 4680 | return [flag for flag, requested in options if requested] |
| 4681 | |
| 4682 | |
| 4683 | def _main( |
| 4684 | parser: argparse.ArgumentParser, |
| 4685 | args: argparse.Namespace, |
| 4686 | extra_argv: list[str], |
| 4687 | *, |
| 4688 | command_started: float | None = None, |
| 4689 | ) -> int: |
| 4690 | if command_started is None: |
| 4691 | command_started = time.monotonic() |
| 4692 | finalization_deadline = command_started + pipeline.FINALIZATION_WORK_CUTOFF_SECONDS |
| 4693 | if args.include_research_backend and not args.diagnose: |
| 4694 | parser.error("--include-research-backend requires --diagnose") |
| 4695 | if args.record_fixtures and (args.diagnose or args.preflight): |
| 4696 | flag = "--preflight" if args.preflight else "--diagnose" |
| 4697 | sys.stderr.write(f"[last30days] --record-fixtures cannot be combined with {flag}.\n") |
| 4698 | return 2 |
| 4699 | if args.debug: |
| 4700 | os.environ["LAST30DAYS_DEBUG"] = "1" |
| 4701 | |
| 4702 | if args.cached_report and ( |
| 4703 | args.emit != "html" or not args.synthesis_file or not args.topic or args.deep_research |
| 4704 | or args.plan or args.competitors_plan or args.x_posts or args.reddit_threads |
| 4705 | or args.shortform_urls |
| 4706 | or args.discover is not None or args.drill or args.diagnose or args.preflight |
| 4707 | or args.welcome or args.resolve_save_dir or args.resolve_browser_consent |
| 4708 | or args.verify_freshness is True |
| 4709 | ): |
| 4710 | parser.error("--cached-report requires a topic, --emit=html, and --synthesis-file without research input files, --verify-freshness, or other command modes") |
| 4711 | topic = " ".join(args.topic).strip() |
| 4712 | cached_followup = ( |
| 4713 | not topic and (args.drill or args.verify_freshness is True) |
| 4714 | and args.discover is None |
| 4715 | and not ( |
| 4716 | args.diagnose or args.preflight or args.welcome |
| 4717 | or args.resolve_save_dir or args.resolve_browser_consent |
| 4718 | ) |
| 4719 | ) |
| 4720 | if args.followup_topic is not None and (not cached_followup or not args.followup_topic.strip()): |
| 4721 | parser.error("--followup-topic requires a nonempty topic and --drill or post-run --verify-freshness") |
| 4722 | if args.followup_run is not None and (not cached_followup or not re.fullmatch(r"[0-9a-f]{32}", args.followup_run)): |
| 4723 | parser.error("--followup-run requires a cache ID and --drill or post-run --verify-freshness") |
| 4724 | if cached_followup and any( |
| 4725 | value is not None |
| 4726 | for value in (args.x_posts, args.reddit_threads, args.shortform_urls, args.plan, args.competitors_plan) |
| 4727 | ): |
| 4728 | parser.error("cached follow-ups use saved evidence and do not accept new plans or envelope files") |
| 4729 | if args.welcome: |
| 4730 | from lib import setup_wizard |
| 4731 | print(setup_wizard.render_welcome()) |
| 4732 | return 0 |
| 4733 | person_exit = _person_inputs_gate(args, topic) |
| 4734 | if person_exit is not None: |
| 4735 | return person_exit |
| 4736 | |
| 4737 | original_topic = topic |
| 4738 | try: |
| 4739 | requested_window = ( |
| 4740 | dates.get_date_range( |
| 4741 | 30 if args.lookback_days is None else args.lookback_days, |
| 4742 | as_of_date=args.as_of_date, |
| 4743 | ) |
| 4744 | if not args.cached_report or args.lookback_days is not None or args.as_of_date is not None else None |
| 4745 | ) |
| 4746 | except ValueError as exc: |
| 4747 | parser.error(str(exc)) |
| 4748 | command_topic = "" if args.research_only or args.cached_report else topic.lower() |
| 4749 | _validate_extra_argv(parser, command_topic, extra_argv) |
| 4750 | if args.resolve_save_dir: |
| 4751 | try: |
| 4752 | print(env.resolve_memory_dir(args.save_dir)) |
| 4753 | except ValueError as exc: |
| 4754 | sys.stderr.write(f"[last30days] {exc}\n") |
| 4755 | return 2 |
| 4756 | return 0 |
| 4757 | if args.resolve_browser_consent: |
| 4758 | granted = not args.no_browser_cookies and env.has_recorded_browser_consent() |
| 4759 | print("granted" if granted else "not-granted") |
| 4760 | return 0 |
| 4761 | if args.x_posts is not None and _looks_inline_json(args.x_posts): |
| 4762 | sys.stderr.write( |
| 4763 | "[last30days] --x-posts accepts a file path only (inline JSON is not " |
| 4764 | "accepted); write the envelope to a .json file and pass its path.\n" |
| 4765 | ) |
| 4766 | return 2 |
| 4767 | if args.reddit_threads is not None and reddit_envelope.looks_inline_json(args.reddit_threads): |
| 4768 | sys.stderr.write( |
| 4769 | "[last30days] --reddit-threads accepts a file path or '-' only (inline " |
| 4770 | "JSON is not accepted); write the envelope to a .json file and pass its path.\n" |
| 4771 | ) |
| 4772 | return 2 |
| 4773 | if args.shortform_urls is not None and shortform_envelope.looks_inline_json(args.shortform_urls): |
| 4774 | sys.stderr.write( |
| 4775 | "[last30days] --shortform-urls accepts a file path or '-' only (inline " |
| 4776 | "JSON is not accepted); write the envelope to a .json file and pass its path.\n" |
| 4777 | ) |
| 4778 | return 2 |
| 4779 | if args.publish and command_topic != "library feed": |
| 4780 | sys.stderr.write( |
| 4781 | "[last30days] --publish is only supported by the 'library feed' command.\n" |
| 4782 | ) |
| 4783 | return 2 |
| 4784 | if ( |
| 4785 | args.harvest_source is not None |
| 4786 | or args.harvest_since is not None |
| 4787 | or args.dry_run |
| 4788 | ) and command_topic != "library harvest": |
| 4789 | sys.stderr.write( |
| 4790 | "[last30days] --source, --since, and --dry-run are only supported by the 'library harvest' command.\n" |
| 4791 | ) |
| 4792 | return 2 |
| 4793 | if (args.preflight or args.diagnose) and _is_admin_command(command_topic): |
| 4794 | flag = "--preflight" if args.preflight else "--diagnose" |
| 4795 | sys.stderr.write( |
| 4796 | f"[last30days] {flag} cannot be combined with the '{command_topic}' " |
| 4797 | "command. Omit it to run the command, or pass --research-only to " |
| 4798 | "inspect a research topic with that name.\n" |
| 4799 | ) |
| 4800 | return 2 |
| 4801 | if command_topic == "setup": |
| 4802 | # Persisting a credential or managing local hook configs needs no |
| 4803 | # config load (no Keychain / pass probes, no cookie policy), so these |
| 4804 | # dispatch before get_config. |
| 4805 | store_key_present, store_key_name, _ = _split_store_key(extra_argv) |
| 4806 | if store_key_present: |
| 4807 | return _run_store_key(store_key_name) |
| 4808 | install_target, uninstall_target, _ = _split_hook_flags(extra_argv) |
| 4809 | if install_target is not None or uninstall_target is not None: |
| 4810 | return _run_hook_setup(install_target, uninstall_target) |
| 4811 | |
| 4812 | config_policy = _config_policy_for_args(args, topic, extra_argv) |
| 4813 | hosted_deferred_local_load = ( |
| 4814 | not args.diagnose |
| 4815 | and not args.preflight |
| 4816 | and not _is_admin_command(command_topic) |
| 4817 | and not args.mock |
| 4818 | and not args.finalize |
| 4819 | and not _has_invalid_cli_combination(args, topic) |
| 4820 | and _will_tentatively_use_hosted_api(args, topic) |
| 4821 | ) |
| 4822 | config = env.get_config(policy=config_policy) |
| 4823 | if args.no_research_persistence: |
| 4824 | config["_no_research_persistence"] = True |
| 4825 | if args.perplexity_search_type is not None: |
| 4826 | config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"] = args.perplexity_search_type |
| 4827 | # One memo per command: comparison mode runs pipeline.run per entity in |
| 4828 | # parallel, so the reset must not live inside the pipeline. |
| 4829 | http.reset_reddit_keyless_memo() |
| 4830 | reddit.reset_scrapecreators_memo() |
| 4831 | reddit_arctic.reset_memo() |
| 4832 | reddit_search.reset_run_state() |
| 4833 | reddit_discover.reset_run_state() |
| 4834 | reddit_health.reset_run_state() |
| 4835 | reddit_session.reset_run_state() |
| 4836 | web_search_keyless.reset_rung_health() |
| 4837 | is_recordable_research = ( |
| 4838 | bool(topic) or bool(args.drill) or (args.discover is not None and not args.finalize) |
| 4839 | ) |
| 4840 | if ( |
| 4841 | args.record_fixtures |
| 4842 | and is_recordable_research |
| 4843 | and not _is_admin_command(command_topic) |
| 4844 | and not (args.diagnose or args.preflight or args.welcome or args.cached_report) |
| 4845 | and reddit_session.gate(config)[0] |
| 4846 | ): |
| 4847 | # Recorded fixtures are shared artifacts; a logged-in session's pages |
| 4848 | # (and its cookie) must never reach one. |
| 4849 | sys.stderr.write( |
| 4850 | "[last30days] --record-fixtures refuses to run while the logged-in Reddit " |
| 4851 | "session is on. Re-run with --no-browser-cookies, or set " |
| 4852 | "REDDIT_BROWSER_CONSENT=false, to record without it.\n" |
| 4853 | ) |
| 4854 | return 2 |
| 4855 | fetch_memo.reset() |
| 4856 | resolved_corpus_dirs = corpus.resolve_directories( |
| 4857 | args.corpus, config.get("LAST30DAYS_CORPUS_DIRS") |
| 4858 | ) |
| 4859 | # EXCLUDE_SOURCES=corpus disables corpus retrieval entirely; the hosted |
| 4860 | # privacy bypass below must use the same predicate, or hosted users with |
| 4861 | # configured-but-excluded dirs silently lose the remote backend. |
| 4862 | excluded_sources = { |
| 4863 | value.strip().lower() |
| 4864 | for value in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 4865 | if value.strip() |
| 4866 | } |
| 4867 | if "corpus" in excluded_sources: |
| 4868 | resolved_corpus_dirs = [] |
| 4869 | if resolved_corpus_dirs: |
| 4870 | config["_CORPUS_DIRS"] = [str(path) for path in resolved_corpus_dirs] |
| 4871 | if _config_truthy(config.get("LAST30DAYS_CORPUS_IN_EXPORT")): |
| 4872 | config["_CORPUS_IN_EXPORT"] = True |
| 4873 | external_plan = None |
| 4874 | if args.plan: |
| 4875 | import json as _json |
| 4876 | plan_str = args.plan |
| 4877 | if plan_str == "-": |
| 4878 | try: |
| 4879 | stdin_buffer = getattr(sys.stdin, "buffer", None) |
| 4880 | plan_str = ( |
| 4881 | stdin_buffer.read().decode("utf-8") |
| 4882 | if stdin_buffer is not None else sys.stdin.read() |
| 4883 | ) |
| 4884 | except (OSError, UnicodeDecodeError) as exc: |
| 4885 | sys.stderr.write(f"[Planner] Cannot read --plan stdin: {exc}\n") |
| 4886 | raise SystemExit(2) |
| 4887 | elif os.path.isfile(plan_str): |
| 4888 | try: |
| 4889 | with open(plan_str, encoding="utf-8") as f: |
| 4890 | plan_str = f.read() |
| 4891 | except (OSError, UnicodeDecodeError) as exc: |
| 4892 | sys.stderr.write(f"[Planner] Cannot read --plan file: {exc}\n") |
| 4893 | raise SystemExit(2) |
| 4894 | try: |
| 4895 | external_plan = _json.loads(plan_str) |
| 4896 | except _json.JSONDecodeError as exc: |
| 4897 | sys.stderr.write(f"[Planner] Invalid --plan JSON: {exc}\n") |
| 4898 | # Fail fast instead of silently dropping to the internal planner |
| 4899 | # and burning a paid run the user did not ask for. Mirrors the |
| 4900 | # --plan file-read branch above and parse_competitors_plan. |
| 4901 | raise SystemExit(2) |
| 4902 | from lib import planner as _plan_validator |
| 4903 | try: |
| 4904 | _plan_validator.validate_external_plan(external_plan) |
| 4905 | except ValueError as exc: |
| 4906 | sys.stderr.write(f"[Planner] Invalid --plan schema: {exc}.\n") |
| 4907 | raise SystemExit(2) |
| 4908 | |
| 4909 | research_options = _cache_research_options( |
| 4910 | args, config, supplied_only=args.cached_report, |
| 4911 | resolved_corpus_dirs=resolved_corpus_dirs, external_plan=external_plan, |
| 4912 | ) |
| 4913 | _propagate_config_to_environ(config) |
| 4914 | |
| 4915 | # Env-var fallback for --save-dir, mirroring the LAST30DAYS_STORE pattern below. |
| 4916 | # Uses `is None` / `is not None` checks (not truthy `or`) at every layer so that |
| 4917 | # `--save-dir ""`, `LAST30DAYS_MEMORY_DIR=""` (shell-export-empty), and explicit |
| 4918 | # absence each correctly suppress save. An `or` chain would collapse the empty |
| 4919 | # shell-export into the same path as unset, silently falling through to .env. |
| 4920 | if args.save_dir is None: |
| 4921 | env_val = os.environ.get("LAST30DAYS_MEMORY_DIR") |
| 4922 | args.save_dir = env_val if env_val is not None else config.get("LAST30DAYS_MEMORY_DIR") |
| 4923 | |
| 4924 | # Surface SSH-routing config as an env var so library modules (e.g. |
| 4925 | # youtube_yt) can read it without taking a config dependency. This |
| 4926 | # routes yt-dlp through `ssh <host>` to bypass YouTube's bot-wall on |
| 4927 | # datacenter IPs (see lib/youtube_yt.py for details). |
| 4928 | if config.get("LAST30DAYS_YOUTUBE_SSH_HOST") and "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ: |
| 4929 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = config["LAST30DAYS_YOUTUBE_SSH_HOST"] |
| 4930 | # Surface YOUTUBE_PROXY / YT_PROXY so youtube_yt can read them without a |
| 4931 | # config dependency. Shell-set values take precedence over .env values. |
| 4932 | if config.get("YOUTUBE_PROXY") and "YOUTUBE_PROXY" not in os.environ: |
| 4933 | os.environ["YOUTUBE_PROXY"] = config["YOUTUBE_PROXY"] |
| 4934 | if config.get("YT_PROXY") and "YT_PROXY" not in os.environ: |
| 4935 | os.environ["YT_PROXY"] = config["YT_PROXY"] |
| 4936 | |
| 4937 | if args.preflight: |
| 4938 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 4939 | if save_dir_exit is not None: |
| 4940 | return save_dir_exit |
| 4941 | requested_sources = resolve_requested_sources(args.search, config) |
| 4942 | preflight_config = pipeline.with_plan_source_omissions(config, external_plan) |
| 4943 | diag = pipeline.diagnose(preflight_config, requested_sources, safe=True) |
| 4944 | hosted_bypassed = bool( |
| 4945 | args.cached_report |
| 4946 | or args.mock |
| 4947 | or args.record_fixtures |
| 4948 | or args.discover is not None |
| 4949 | or args.drill |
| 4950 | or ( |
| 4951 | args.perplexity_search_type is not None |
| 4952 | and _preflight_has_perplexity_key_for_research(args, topic, extra_argv, config) |
| 4953 | ) |
| 4954 | ) |
| 4955 | preflight = permission_preflight.build( |
| 4956 | preflight_config, |
| 4957 | diag, |
| 4958 | planned_save_dir=args.save_dir, |
| 4959 | report_on_save_dir=( |
| 4960 | None if args.no_research_persistence else args.preflight_report_on_save_dir |
| 4961 | ), |
| 4962 | requested_sources=requested_sources, |
| 4963 | deep_research=bool(getattr(args, "deep_research", False)), |
| 4964 | local_only_run=hosted_bypassed, |
| 4965 | ) |
| 4966 | _add_preflight_research_writes(preflight, args, config) |
| 4967 | if args.emit == "json": |
| 4968 | print(json.dumps(preflight, indent=2, sort_keys=True)) |
| 4969 | else: |
| 4970 | print(permission_preflight.render_text(preflight), end="") |
| 4971 | return 0 |
| 4972 | |
| 4973 | # Handle doctor subcommand: topic-word dispatch mirroring setup (exact |
| 4974 | # match only, so multi-word research topics containing "doctor" still |
| 4975 | # research normally). Aggregates probes/descriptors/prescriptions into |
| 4976 | # one grouped health surface; always exits 0. |
| 4977 | if command_topic == "doctor": |
| 4978 | from lib import doctor |
| 4979 | return doctor.run( |
| 4980 | config, |
| 4981 | emit_json=(args.emit == "json" or "--json" in extra_argv), |
| 4982 | cached="--cached" in extra_argv, |
| 4983 | postmortem="--postmortem" in extra_argv, |
| 4984 | probe="--probe" in extra_argv, |
| 4985 | ) |
| 4986 | |
| 4987 | if command_topic == "library feed": |
| 4988 | return _run_library_feed(args, config) |
| 4989 | if command_topic == "library harvest": |
| 4990 | return _run_library_harvest(args, config) |
| 4991 | if command_topic == "library search" or command_topic.startswith("library search "): |
| 4992 | return _run_library_search(args, config, topic[len("library search") :].strip()) |
| 4993 | |
| 4994 | if command_topic == "queue list": |
| 4995 | return _run_queue_list(args, config) |
| 4996 | if command_topic == "queue cover" or command_topic.startswith("queue cover "): |
| 4997 | return _run_queue_cover(args, config, topic[len("queue cover") :].strip()) |
| 4998 | |
| 4999 | # Handle setup subcommand |
| 5000 | if command_topic == "setup": |
| 5001 | from lib import setup_wizard |
| 5002 | if "--openclaw" in extra_argv: |
| 5003 | results = setup_wizard.run_openclaw_setup(config) |
| 5004 | print(json.dumps(results)) |
| 5005 | return 0 |
| 5006 | if "--reddit-session" in extra_argv or "--no-reddit-session" in extra_argv: |
| 5007 | if "--reddit-session" in extra_argv and "--no-reddit-session" in extra_argv: |
| 5008 | sys.stderr.write("[last30days] pass --reddit-session or --no-reddit-session, not both.\n") |
| 5009 | return 2 |
| 5010 | consent = "--reddit-session" in extra_argv |
| 5011 | if consent and args.no_browser_cookies: |
| 5012 | sys.stderr.write("[last30days] --no-browser-cookies refuses the Reddit login read.\n") |
| 5013 | return 2 |
| 5014 | results = setup_wizard.run_reddit_session_setup(config, env.CONFIG_FILE, consent=consent) |
| 5015 | print(json.dumps(results)) |
| 5016 | return 0 |
| 5017 | if any(f in extra_argv for f in ("--github", "--device-auth", "--github-start", "--github-poll")): |
| 5018 | if "--github-start" in extra_argv: |
| 5019 | results = setup_wizard.run_github_start() |
| 5020 | elif "--github-poll" in extra_argv: |
| 5021 | results = setup_wizard.run_github_poll() |
| 5022 | elif "--github" in extra_argv: |
| 5023 | results = setup_wizard.run_github_auth() |
| 5024 | else: |
| 5025 | results = setup_wizard.run_full_device_auth() |
| 5026 | # Persist the returned key so the paid sources activate on the next |
| 5027 | # run, and mask it in stdout so the secret never lands in the host |
| 5028 | # model's captured Bash output. |
| 5029 | api_key = results.get("api_key") |
| 5030 | status = results.get("status") |
| 5031 | if api_key: |
| 5032 | if status == "success": |
| 5033 | results["persisted"] = setup_wizard.write_api_key(env.CONFIG_FILE, api_key) |
| 5034 | elif status == "already_registered": |
| 5035 | results["persisted"] = True # key was already saved |
| 5036 | else: |
| 5037 | results.setdefault("persisted", False) |
| 5038 | # Mask for EVERY status that carries a key, not just success, so |
| 5039 | # the raw secret never reaches the host model's captured stdout. |
| 5040 | results["api_key"] = setup_wizard.mask_api_key(api_key) |
| 5041 | else: |
| 5042 | results["persisted"] = False |
| 5043 | print(json.dumps(results)) |
| 5044 | return 0 |
| 5045 | reuse_browser_consent = USE_RECORDED_BROWSER_CONSENT_FLAG in extra_argv |
| 5046 | if reuse_browser_consent and config.get("_BROWSER_COOKIE_MODE") != "read": |
| 5047 | print("not-granted") |
| 5048 | return 0 |
| 5049 | fresh_browser_consent = _setup_has_fresh_browser_consent(args, extra_argv) |
| 5050 | sys.stderr.write("Running auto-setup...\n") |
| 5051 | results = setup_wizard.run_auto_setup( |
| 5052 | config, |
| 5053 | allow_browser_cookies=reuse_browser_consent or fresh_browser_consent, |
| 5054 | ) |
| 5055 | # Keep only successful browsers, including distinct service winners; |
| 5056 | # "auto" would also probe browsers that did not supply any cookies. |
| 5057 | found_browsers = dict.fromkeys( |
| 5058 | "firefox" if browser == "firefox-wsl" else browser |
| 5059 | for browser in results.get("cookies_found", {}).values() |
| 5060 | ) |
| 5061 | from_browser = ",".join(found_browsers) or None |
| 5062 | denied_browsers = ( |
| 5063 | results.get("x_cookie_access_denied", []) |
| 5064 | if results.get("browser_cookie_scan_attempted") else [] |
| 5065 | ) |
| 5066 | prior_denial = config.get("LAST30DAYS_X_COOKIE_ACCESS_DENIED") |
| 5067 | denial_marker = ( |
| 5068 | ",".join(denied_browsers) or ("none" if prior_denial else None) |
| 5069 | if results.get("browser_cookie_scan_attempted") else None |
| 5070 | ) |
| 5071 | results["env_written"] = setup_wizard.write_setup_config( |
| 5072 | env.CONFIG_FILE, |
| 5073 | from_browser=from_browser, |
| 5074 | x_cookie_access_denied=denial_marker, |
| 5075 | browser_consent=None if args.diagnose or reuse_browser_consent else fresh_browser_consent, |
| 5076 | ) |
| 5077 | if not results["env_written"]: |
| 5078 | sys.stderr.write("Setup configuration could not be fully saved; some settings may already be saved.\n") |
| 5079 | return 1 |
| 5080 | sys.stderr.write(setup_wizard.get_setup_status_text(results) + "\n") |
| 5081 | return 0 |
| 5082 | |
| 5083 | # Reject whitespace-only save dirs for commands that consume save_dir |
| 5084 | # (discover, drill, cached freshness, hosted/local research), while letting |
| 5085 | # diagnostic/setup commands (doctor, --diagnose, setup) run and report the |
| 5086 | # misconfiguration. |
| 5087 | if not args.diagnose: |
| 5088 | save_dir_exit = _validate_save_dir(args.save_dir) |
| 5089 | if save_dir_exit is not None: |
| 5090 | return save_dir_exit |
| 5091 | |
| 5092 | # Bare --discover (no domain) is global trending, so the dispatch keys on |
| 5093 | # "flag present" (is not None), never on the domain string's truthiness. |
| 5094 | if args.deep_research and not topic and not args.diagnose: |
| 5095 | sys.stderr.write( |
| 5096 | "[last30days] --deep-research requires a normal positional topic; " |
| 5097 | "it cannot be combined with discovery, drill, or cached-only modes.\n" |
| 5098 | ) |
| 5099 | return 2 |
| 5100 | |
| 5101 | if args.discover is not None and not args.diagnose: |
| 5102 | if topic: |
| 5103 | sys.stderr.write( |
| 5104 | "[last30days] --discover supplies the domain and cannot be combined " |
| 5105 | "with a positional topic.\n" |
| 5106 | ) |
| 5107 | return 2 |
| 5108 | if args.drill: |
| 5109 | sys.stderr.write("[last30days] --discover and --drill are mutually exclusive.\n") |
| 5110 | return 2 |
| 5111 | # Shared guards for EVERY discover invocation - the one-shot and all |
| 5112 | # three protocol legs - hoisted here so no leg can drift: discovery |
| 5113 | # sweeps live listings (never --as-of) and has no HTML pipeline yet. |
| 5114 | if args.as_of_date: |
| 5115 | sys.stderr.write( |
| 5116 | "[last30days] --as-of cannot be used with --discover because discovery " |
| 5117 | "sweeps current live listings.\n" |
| 5118 | ) |
| 5119 | return 2 |
| 5120 | if args.emit == "html" or args.publish_html: |
| 5121 | sys.stderr.write("[last30days] discovery mode does not support HTML publishing yet.\n") |
| 5122 | return 2 |
| 5123 | # The three protocol legs are one-leg-per-invocation: each pairing |
| 5124 | # below asks for two legs at once, so name the combination and stop. |
| 5125 | # (--judgments/--angles dispatch on presence, never path truthiness.) |
| 5126 | for first, second, conflict in ( |
| 5127 | ("--nominate-only", "--judgments", args.nominate_only and args.judgments is not None), |
| 5128 | ("--nominate-only", "--finalize", args.nominate_only and args.finalize), |
| 5129 | ("--judgments", "--finalize", args.judgments is not None and args.finalize), |
| 5130 | ): |
| 5131 | if conflict: |
| 5132 | sys.stderr.write( |
| 5133 | f"[last30days] {first} and {second} are mutually exclusive: " |
| 5134 | "each runs a different leg of the discovery protocol.\n" |
| 5135 | ) |
| 5136 | return 2 |
| 5137 | if args.angles is not None and not args.finalize: |
| 5138 | sys.stderr.write( |
| 5139 | "[last30days] --angles only applies to --discover --finalize " |
| 5140 | "runs; add --finalize or drop the flag.\n" |
| 5141 | ) |
| 5142 | return 2 |
| 5143 | protocol_leg = ( |
| 5144 | args.nominate_only or args.judgments is not None or args.finalize |
| 5145 | ) |
| 5146 | if protocol_leg and args.mock and not args.save_dir: |
| 5147 | # Truthiness is right here: an empty --save-dir/env value means |
| 5148 | # "no save dir", and handoff state would land in the real config |
| 5149 | # dir - a side effect mock runs must never have. |
| 5150 | sys.stderr.write( |
| 5151 | "[last30days] mock protocol legs require --save-dir to stay " |
| 5152 | "side-effect-free: --mock with --nominate-only/--judgments/" |
| 5153 | "--finalize would otherwise write handoff state into the real " |
| 5154 | "config dir.\n" |
| 5155 | ) |
| 5156 | return 2 |
| 5157 | # --discover --judgments runs a multi-wave enrichment batch with its own |
| 5158 | # LAST30DAYS_ENRICH_BUDGET_SECONDS (default 450s) budget; injecting the |
| 5159 | # 280s foreground cutoff here aborts transcript backfill and reranking |
| 5160 | # for every topic finalizing past 280s. |
| 5161 | if args.judgments is None: |
| 5162 | config = {**config, "_finalization_deadline": finalization_deadline} |
| 5163 | if protocol_leg: |
| 5164 | return _run_discover_protocol_leg(args, config) |
| 5165 | return _run_discover(args, config) |
| 5166 | |
| 5167 | if args.discover_shallow and not args.diagnose: |
| 5168 | # Without --discover this flag would silently no-op into a full |
| 5169 | # research run - reject it instead of ignoring the requested mode. |
| 5170 | sys.stderr.write( |
| 5171 | "[last30days] --discover-shallow only applies to --discover runs; " |
| 5172 | "add --discover [domain] or drop the flag.\n" |
| 5173 | ) |
| 5174 | return 2 |
| 5175 | |
| 5176 | # Same orphan rule for every protocol-leg flag: without --discover each |
| 5177 | # would silently no-op into a normal research run. |
| 5178 | if not args.diagnose: |
| 5179 | for flag_label, present in ( |
| 5180 | ("--nominate-only", args.nominate_only), |
| 5181 | ("--judgments", args.judgments is not None), |
| 5182 | ("--finalize", args.finalize), |
| 5183 | ): |
| 5184 | if present: |
| 5185 | sys.stderr.write( |
| 5186 | f"[last30days] {flag_label} only applies to --discover runs; " |
| 5187 | "add --discover [domain] or drop the flag.\n" |
| 5188 | ) |
| 5189 | return 2 |
| 5190 | if args.angles is not None: |
| 5191 | sys.stderr.write( |
| 5192 | "[last30days] --angles only applies to --discover --finalize runs; " |
| 5193 | "add --discover --finalize or drop the flag.\n" |
| 5194 | ) |
| 5195 | return 2 |
| 5196 | |
| 5197 | if args.drill and not args.diagnose: |
| 5198 | if topic: |
| 5199 | sys.stderr.write( |
| 5200 | "[last30days] --drill uses the cached topic and cannot be " |
| 5201 | "combined with a new topic.\n" |
| 5202 | ) |
| 5203 | return 2 |
| 5204 | publish_exit = _validate_publish_html(args) |
| 5205 | if publish_exit is not None: |
| 5206 | return publish_exit |
| 5207 | if args.dedicated_subreddits: |
| 5208 | config["_dedicated_subreddits"] = [ |
| 5209 | value.strip().removeprefix("r/") |
| 5210 | for value in args.dedicated_subreddits.split(",") |
| 5211 | if value.strip() |
| 5212 | ] |
| 5213 | if args.polymarket_keywords: |
| 5214 | config["_polymarket_keywords"] = [ |
| 5215 | value.strip().lower() |
| 5216 | for value in args.polymarket_keywords.split(",") |
| 5217 | if value.strip() |
| 5218 | ] |
| 5219 | return _run_drill(args, {**config, "_finalization_deadline": finalization_deadline}) |
| 5220 | |
| 5221 | if args.verify_freshness and not topic and not args.diagnose: |
| 5222 | publish_exit = _validate_publish_html(args) |
| 5223 | if publish_exit is not None: |
| 5224 | return publish_exit |
| 5225 | return _run_cached_freshness(args, config) |
| 5226 | |
| 5227 | if args.deep_research and not args.diagnose: |
| 5228 | if _comparison_requested(args, topic): |
| 5229 | sys.stderr.write( |
| 5230 | "Error: --deep-research cannot be combined with competitor or vs-mode. " |
| 5231 | "It permits one paid Deep Research run per user action; run each topic " |
| 5232 | "separately.\n" |
| 5233 | ) |
| 5234 | return 2 |
| 5235 | if not ( |
| 5236 | config.get("PERPLEXITY_API_KEY") |
| 5237 | or config.get("OPENROUTER_API_KEY") |
| 5238 | ): |
| 5239 | print( |
| 5240 | "Error: --deep-research requires PERPLEXITY_API_KEY or " |
| 5241 | "OPENROUTER_API_KEY", |
| 5242 | file=sys.stderr, |
| 5243 | ) |
| 5244 | return 1 |
| 5245 | config["_deep_research"] = True |
| 5246 | try: |
| 5247 | enable_deep_research_source(config) |
| 5248 | except ValueError as exc: |
| 5249 | print(f"Error: {exc}", file=sys.stderr) |
| 5250 | return 2 |
| 5251 | |
| 5252 | # Reject a misspelled configured register before remote submission or any |
| 5253 | # local source retrieval. Excluded modes resolve to default and remain |
| 5254 | # unaffected by the register setting. |
| 5255 | try: |
| 5256 | _audience_register_for_run(args, config, None) |
| 5257 | except ValueError as exc: |
| 5258 | sys.stderr.write(f"[last30days] {exc}\n") |
| 5259 | return 2 |
| 5260 | |
| 5261 | # Remote API path: when BOTH LAST30DAYS_API_KEY and LAST30DAYS_API_BASE are |
| 5262 | # set (and --mock is not), the search runs through the configured remote API |
| 5263 | # instead of local sources; no local provider keys are needed (see |
| 5264 | # lib/hosted.py). With either env var unset, behavior below is byte-identical |
| 5265 | # to local-only runs - there is no built-in endpoint. LAST30DAYS_API_MODE=proxy |
| 5266 | # keeps the run local and sends only paid provider calls through the API |
| 5267 | # key's metered proxy (lib/proxy.py). |
| 5268 | if topic and env.proxy_mode_requested() and not proxy.configured(): |
| 5269 | sys.stderr.write( |
| 5270 | "[last30days] LAST30DAYS_API_MODE=proxy needs LAST30DAYS_API_KEY and an https " |
| 5271 | "LAST30DAYS_API_BASE; paid sources without their own key stay off.\n" |
| 5272 | ) |
| 5273 | if ( |
| 5274 | topic |
| 5275 | and resolved_corpus_dirs |
| 5276 | and env.hosted_backend_configured() |
| 5277 | ): |
| 5278 | sys.stderr.write( |
| 5279 | "[last30days] Local corpus configured; bypassing the hosted backend so files stay on this machine.\n" |
| 5280 | ) |
| 5281 | # An explicit --perplexity-search-type is per-invocation intent the hosted |
| 5282 | # backend cannot honor, so it runs locally, but only when a direct |
| 5283 | # PERPLEXITY_API_KEY can apply it; otherwise the switch would trade hosted |
| 5284 | # coverage for nothing. Key on the parsed CLI flag only: a value from |
| 5285 | # LAST30DAYS_PERPLEXITY_SEARCH_TYPE must never move routing. |
| 5286 | elif ( |
| 5287 | topic |
| 5288 | and args.perplexity_search_type is not None |
| 5289 | and config.get("PERPLEXITY_API_KEY") |
| 5290 | and not args.diagnose |
| 5291 | and not args.mock |
| 5292 | and not args.record_fixtures |
| 5293 | and not args.deep_research |
| 5294 | and env.hosted_backend_configured() |
| 5295 | ): |
| 5296 | sys.stderr.write( |
| 5297 | "[last30days] --perplexity-search-type set; bypassing the hosted backend " |
| 5298 | "because it does not apply the Perplexity search type.\n" |
| 5299 | ) |
| 5300 | uses_hosted_api = ( |
| 5301 | env.hosted_backend_configured() |
| 5302 | and not args.cached_report |
| 5303 | and not args.mock |
| 5304 | and not args.record_fixtures |
| 5305 | and not resolved_corpus_dirs |
| 5306 | and not args.deep_research |
| 5307 | and (args.perplexity_search_type is None or not config.get("PERPLEXITY_API_KEY")) |
| 5308 | ) |
| 5309 | # Validate hosted-only clarification flags before reloading local cookies or |
| 5310 | # Keychain/pass secrets on a local bypass. |
| 5311 | if (args.clarify_angle is not None or args.clarify_broadly) and not ( |
| 5312 | topic and not args.diagnose and uses_hosted_api |
| 5313 | ): |
| 5314 | sys.stderr.write( |
| 5315 | "[last30days] --clarify-angle and --clarify-broadly answer a hosted backend " |
| 5316 | "clarification, so they apply only to a hosted run.\n" |
| 5317 | ) |
| 5318 | return 2 |
| 5319 | law7_blocked = bool(_law7_host_plan_signal(args, topic)) |
| 5320 | may_reuse_html_cache = ( |
| 5321 | args.emit == "html" |
| 5322 | and bool(args.synthesis_file) |
| 5323 | and not args.deep_research |
| 5324 | and not args.cached_report |
| 5325 | ) |
| 5326 | target_browser_mode: env.BrowserCookieMode = ( |
| 5327 | "off" if (args.no_browser_cookies or law7_blocked) else "read" |
| 5328 | ) |
| 5329 | if ( |
| 5330 | hosted_deferred_local_load |
| 5331 | and topic |
| 5332 | and not args.diagnose |
| 5333 | and not uses_hosted_api |
| 5334 | and (not law7_blocked or may_reuse_html_cache) |
| 5335 | and ( |
| 5336 | config_policy.browser_cookies != target_browser_mode |
| 5337 | or not config_policy.load_secret_stores |
| 5338 | ) |
| 5339 | ): |
| 5340 | # Confirmed local fallback (corpus or direct Perplexity key); reload |
| 5341 | # secret stores (and browser cookies only when research can run, never |
| 5342 | # on a LAW-7-blocked HTML cache-reuse lookup). |
| 5343 | config = env.get_config( |
| 5344 | policy=env.ConfigLoadPolicy( |
| 5345 | browser_cookies=target_browser_mode, |
| 5346 | load_secret_stores=True, |
| 5347 | ) |
| 5348 | ) |
| 5349 | if args.no_research_persistence: |
| 5350 | config["_no_research_persistence"] = True |
| 5351 | if args.perplexity_search_type is not None: |
| 5352 | config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"] = args.perplexity_search_type |
| 5353 | if resolved_corpus_dirs: |
| 5354 | config["_CORPUS_DIRS"] = [str(path) for path in resolved_corpus_dirs] |
| 5355 | if _config_truthy(config.get("LAST30DAYS_CORPUS_IN_EXPORT")): |
| 5356 | config["_CORPUS_IN_EXPORT"] = True |
| 5357 | _propagate_config_to_environ(config) |
| 5358 | research_options = _cache_research_options( |
| 5359 | args, config, supplied_only=args.cached_report, |
| 5360 | resolved_corpus_dirs=resolved_corpus_dirs, external_plan=external_plan, |
| 5361 | ) |
| 5362 | if topic and not args.diagnose and uses_hosted_api: |
| 5363 | if args.require_local_report: |
| 5364 | sys.stderr.write( |
| 5365 | "[last30days] Watchlist requires structured local reports. " |
| 5366 | "Unset LAST30DAYS_API_BASE in the watchlist environment to run locally.\n" |
| 5367 | ) |
| 5368 | return 2 |
| 5369 | unsupported = _unsupported_hosted_options(args) |
| 5370 | if unsupported: |
| 5371 | sys.stderr.write( |
| 5372 | "[last30days] The hosted backend cannot apply these options: " |
| 5373 | f"{', '.join(unsupported)}. Run locally to use them.\n" |
| 5374 | ) |
| 5375 | return 2 |
| 5376 | if _comparison_requested(args, topic): |
| 5377 | sys.stderr.write( |
| 5378 | "[last30days] The hosted backend cannot run comparisons. " |
| 5379 | "Run locally to research each entity.\n" |
| 5380 | ) |
| 5381 | return 2 |
| 5382 | if args.perplexity_search_type is not None: |
| 5383 | sys.stderr.write( |
| 5384 | "hosted backend does not apply --perplexity-search-type and no direct " |
| 5385 | "PERPLEXITY_API_KEY is configured to run it locally; skipping\n" |
| 5386 | ) |
| 5387 | elif config.get("LAST30DAYS_PERPLEXITY_SEARCH_TYPE"): |
| 5388 | sys.stderr.write( |
| 5389 | "hosted backend does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE; skipping\n" |
| 5390 | ) |
| 5391 | if _freshness_enabled(args, config): |
| 5392 | if args.verify_freshness is True: |
| 5393 | sys.stderr.write( |
| 5394 | "[last30days] Freshness verification is not supported by the hosted backend; " |
| 5395 | "run locally or omit --verify-freshness.\n" |
| 5396 | ) |
| 5397 | return 2 |
| 5398 | sys.stderr.write( |
| 5399 | "hosted backend does not support freshness verification; skipping\n" |
| 5400 | ) |
| 5401 | if args.emit == "json" and args.json_profile == "agent": |
| 5402 | sys.stderr.write( |
| 5403 | "[last30days] --json-profile=agent requires the local Report; " |
| 5404 | "the remote API backend only supports --json-profile=raw.\n" |
| 5405 | ) |
| 5406 | return 2 |
| 5407 | if env.reddit_consent_state(config) == "granted": |
| 5408 | sys.stderr.write( |
| 5409 | "[last30days] The logged-in Reddit session is not used with the hosted " |
| 5410 | "backend; no reddit.com cookie is read.\n" |
| 5411 | ) |
| 5412 | if args.x_posts is not None: |
| 5413 | # The envelope is a local-engine contract; the remote API has no |
| 5414 | # lane to receive it. |
| 5415 | sys.stderr.write( |
| 5416 | "[last30days] --x-posts is not supported by the hosted backend; " |
| 5417 | "run locally or omit --x-posts.\n" |
| 5418 | ) |
| 5419 | return 2 |
| 5420 | if args.reddit_threads is not None: |
| 5421 | # Host thread refs are a local-engine contract too. |
| 5422 | sys.stderr.write( |
| 5423 | "[last30days] --reddit-threads is not supported by the hosted backend; " |
| 5424 | "run locally or omit --reddit-threads.\n" |
| 5425 | ) |
| 5426 | return 2 |
| 5427 | if args.shortform_urls is not None: |
| 5428 | sys.stderr.write( |
| 5429 | "[last30days] --shortform-urls is not supported by the hosted backend; " |
| 5430 | "run locally or omit --shortform-urls.\n" |
| 5431 | ) |
| 5432 | return 2 |
| 5433 | from lib import hosted |
| 5434 | depth = "deep" if args.deep else "quick" if args.quick else "default" |
| 5435 | try: |
| 5436 | audience = _audience_register_for_run(args, config, None) |
| 5437 | except ValueError as exc: |
| 5438 | sys.stderr.write(f"[last30days] {exc}\n") |
| 5439 | return 2 |
| 5440 | hosted_kwargs = { |
| 5441 | "emit": args.emit, |
| 5442 | "save_dir": args.save_dir, |
| 5443 | "save_suffix": args.save_suffix or "", |
| 5444 | } |
| 5445 | if audience.name != "default": |
| 5446 | hosted_kwargs["register"] = audience.name |
| 5447 | if args.clarify_angle is not None: |
| 5448 | hosted_kwargs["clarify"] = {"angle": args.clarify_angle} |
| 5449 | elif args.clarify_broadly: |
| 5450 | hosted_kwargs["clarify"] = {"run_broadly": True} |
| 5451 | return hosted.run_hosted(topic, depth, **hosted_kwargs) |
| 5452 | |
| 5453 | if ( |
| 5454 | topic |
| 5455 | and not args.diagnose |
| 5456 | and not args.mock |
| 5457 | and not args.cached_report |
| 5458 | and not args.record_fixtures |
| 5459 | and not args.no_research_persistence |
| 5460 | and not law7_blocked |
| 5461 | ): |
| 5462 | from lib import rust_accel |
| 5463 | bootstrapped = rust_accel.ensure_installed_for_run() |
| 5464 | if bootstrapped and bootstrapped.get("action") in {"installed", "upgraded"}: |
| 5465 | ver = bootstrapped.get("version") |
| 5466 | ver_tag = f" (v{ver})" if ver else "" |
| 5467 | sys.stderr.write(f"[last30days] Installed native Rust core{ver_tag}\n") |
| 5468 | |
| 5469 | if args.lookback_days is None: |
| 5470 | args.lookback_days = 30 |
| 5471 | requested_sources = resolve_requested_sources(args.search, config) |
| 5472 | if args.deep_research: |
| 5473 | requested_sources = add_deep_research_source(requested_sources) |
| 5474 | # Explicit --trustpilot-domain is user intent: activate the opt-in source |
| 5475 | # before diagnose/run so the flag cannot silently no-op (#873). Auto-resolve |
| 5476 | # hints are applied later and must not call this path. |
| 5477 | cli_trustpilot_domain = ( |
| 5478 | args.trustpilot_domain.strip() if args.trustpilot_domain else "" |
| 5479 | ) |
| 5480 | if cli_trustpilot_domain: |
| 5481 | requested_sources = activate_trustpilot_for_explicit_domain( |
| 5482 | config, |
| 5483 | requested_sources, |
| 5484 | reason=f"--trustpilot-domain={cli_trustpilot_domain}", |
| 5485 | ) |
| 5486 | # Explicit --telegram-sources is user intent: activate the opt-in source |
| 5487 | # before diagnose/run so the flag cannot silently no-op (same pattern as |
| 5488 | # Trustpilot #873). Sets TELEGRAM_SOURCES in config for pipeline. |
| 5489 | cli_telegram_sources = ( |
| 5490 | args.telegram_sources.strip() if args.telegram_sources else "" |
| 5491 | ) |
| 5492 | if cli_telegram_sources: |
| 5493 | requested_sources = activate_telegram_for_explicit_sources( |
| 5494 | config, |
| 5495 | requested_sources, |
| 5496 | channels=cli_telegram_sources, |
| 5497 | ) |
| 5498 | # --devto-tags activates the off-by-default dev.to source for this run |
| 5499 | # (the --trustpilot-domain pattern): carried on config for the dispatch, |
| 5500 | # and appended to an explicit or default --search list so it is not |
| 5501 | # filtered back out. EXCLUDE_SOURCES=devto still wins in the pipeline. |
| 5502 | cli_devto_tags = [ |
| 5503 | t.strip() for t in (args.devto_tags or "").split(",") if t.strip() |
| 5504 | ] |
| 5505 | if cli_devto_tags: |
| 5506 | config["_devto_tags"] = cli_devto_tags |
| 5507 | if requested_sources is not None and "devto" not in requested_sources: |
| 5508 | requested_sources = [*requested_sources, "devto"] |
| 5509 | # Host-fetched X envelope: validated before diagnose so a present |
| 5510 | # envelope plans X in (available_sources) and a bad one fails closed here. |
| 5511 | x_posts_envelope: x_envelope.Envelope | None = None |
| 5512 | if args.x_posts is not None: |
| 5513 | if not topic: |
| 5514 | sys.stderr.write("[last30days] --x-posts requires a research topic.\n") |
| 5515 | return 2 |
| 5516 | if _comparison_requested(args, topic): |
| 5517 | sys.stderr.write( |
| 5518 | "[last30days] --x-posts applies to a single-topic run; on a " |
| 5519 | "comparison run pass each entity's envelope through the " |
| 5520 | "x_posts field of its --competitors-plan entry.\n" |
| 5521 | ) |
| 5522 | return 2 |
| 5523 | try: |
| 5524 | x_posts_envelope = _read_x_envelope( |
| 5525 | args.x_posts, topic, args, |
| 5526 | x_handle=args.x_handle, |
| 5527 | x_related=args.x_related.split(",") if args.x_related else None, |
| 5528 | ) |
| 5529 | except x_envelope.EnvelopeContractError as exc: |
| 5530 | sys.stderr.write(f"[last30days] {exc.message}\n") |
| 5531 | return 2 |
| 5532 | # Host-found Reddit thread refs: validated before any research so a bad |
| 5533 | # file fails closed here and the report cache binds to its digest. |
| 5534 | reddit_threads_envelope: reddit_envelope.Envelope | None = None |
| 5535 | reddit_excluded = "reddit" in { |
| 5536 | token.strip().lower() for token in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 5537 | } |
| 5538 | if args.reddit_threads is not None and ( |
| 5539 | reddit_excluded or (requested_sources is not None and "reddit" not in requested_sources) |
| 5540 | ): |
| 5541 | # Reddit is not part of this run: the file is never read, so it can |
| 5542 | # neither stop the run nor change the report cache key. |
| 5543 | sys.stderr.write("[last30days] --reddit-threads ignored: Reddit is not searched this run.\n") |
| 5544 | args.reddit_threads = None |
| 5545 | if args.reddit_threads is not None: |
| 5546 | if not topic: |
| 5547 | sys.stderr.write("[last30days] --reddit-threads requires a research topic.\n") |
| 5548 | return 2 |
| 5549 | if _comparison_requested(args, topic): |
| 5550 | sys.stderr.write( |
| 5551 | "[last30days] --reddit-threads applies to a single-topic run; " |
| 5552 | "omit it on a comparison run.\n" |
| 5553 | ) |
| 5554 | return 2 |
| 5555 | try: |
| 5556 | reddit_threads_envelope = reddit_envelope.read(args.reddit_threads, topic) |
| 5557 | except reddit_envelope.EnvelopeContractError as exc: |
| 5558 | sys.stderr.write(f"[last30days] {exc.message}\n") |
| 5559 | return 2 |
| 5560 | # Host-found TikTok / Instagram URLs: validated up front like the Reddit |
| 5561 | # refs. Only the keyless short-form lane reads them. |
| 5562 | shortform_urls_envelope: shortform_envelope.Envelope | None = None |
| 5563 | if args.shortform_urls is not None: |
| 5564 | excluded = { |
| 5565 | token.strip().lower() for token in str(config.get("EXCLUDE_SOURCES") or "").split(",") |
| 5566 | } |
| 5567 | searched = [ |
| 5568 | name for name in ("tiktok", "instagram") |
| 5569 | if name not in excluded and (requested_sources is None or name in requested_sources) |
| 5570 | ] |
| 5571 | if not searched: |
| 5572 | sys.stderr.write( |
| 5573 | "[last30days] --shortform-urls ignored: TikTok and Instagram are not searched this run.\n" |
| 5574 | ) |
| 5575 | args.shortform_urls = None |
| 5576 | if args.shortform_urls is not None: |
| 5577 | if not topic: |
| 5578 | sys.stderr.write("[last30days] --shortform-urls requires a research topic.\n") |
| 5579 | return 2 |
| 5580 | if _comparison_requested(args, topic): |
| 5581 | sys.stderr.write( |
| 5582 | "[last30days] --shortform-urls applies to a single-topic run; " |
| 5583 | "omit it on a comparison run.\n" |
| 5584 | ) |
| 5585 | return 2 |
| 5586 | try: |
| 5587 | shortform_urls_envelope = shortform_envelope.read(args.shortform_urls, topic) |
| 5588 | except shortform_envelope.EnvelopeContractError as exc: |
| 5589 | sys.stderr.write(f"[last30days] {exc.message}\n") |
| 5590 | return 2 |
| 5591 | if all( |
| 5592 | (env.get_tiktok_token(config) if name == "tiktok" else env.get_instagram_token(config)) |
| 5593 | for name in searched |
| 5594 | ): |
| 5595 | sys.stderr.write( |
| 5596 | "[last30days] --shortform-urls: ScrapeCreators is configured, so it stays the " |
| 5597 | "TikTok/Instagram path; the host URLs are used only if it runs out of credits.\n" |
| 5598 | ) |
| 5599 | if args.diagnose: |
| 5600 | diag = pipeline.diagnose( |
| 5601 | pipeline.with_plan_source_omissions(config, external_plan), |
| 5602 | requested_sources, safe=True, |
| 5603 | x_envelope=x_posts_envelope is not None, |
| 5604 | ) |
| 5605 | if args.include_research_backend: |
| 5606 | diag["research_backend"] = "hosted" if uses_hosted_api else "local" |
| 5607 | print(json.dumps(diag, indent=2, sort_keys=True)) |
| 5608 | return 0 |
| 5609 | |
| 5610 | # Per-entity host-fetched X envelopes are validated here, on the main |
| 5611 | # thread and BEFORE the report-cache lookup, so a bad or stale one fails |
| 5612 | # closed (exit 2) instead of silently dropping that entity inside the |
| 5613 | # fan-out or being served from a cache built while it was still valid. |
| 5614 | comp_plan = parse_competitors_plan(args.competitors_plan) |
| 5615 | try: |
| 5616 | _attach_entity_envelopes(comp_plan, args) |
| 5617 | except x_envelope.EnvelopeContractError as exc: |
| 5618 | sys.stderr.write(f"[last30days] {exc.message}\n") |
| 5619 | return 2 |
| 5620 | |
| 5621 | if not topic: |
| 5622 | parser.print_usage(sys.stderr) |
| 5623 | return 2 |
| 5624 | publish_exit = _validate_publish_html(args) |
| 5625 | if publish_exit is not None: |
| 5626 | return publish_exit |
| 5627 | comp_emit_exit = _validate_comparison_emit( |
| 5628 | args, is_comparison=_comparison_requested(args, topic) |
| 5629 | ) |
| 5630 | if comp_emit_exit is not None: |
| 5631 | return comp_emit_exit |
| 5632 | |
| 5633 | synthesis_md = _resolve_synthesis_md(args) |
| 5634 | |
| 5635 | if not os.environ.get("LAST30DAYS_SKIP_PREFLIGHT"): |
| 5636 | from lib import preflight |
| 5637 | refuse_msg = preflight.check_class_1_trap(topic) |
| 5638 | if refuse_msg: |
| 5639 | sys.stderr.write(refuse_msg) |
| 5640 | return 2 |
| 5641 | |
| 5642 | if ( |
| 5643 | args.emit == "html" |
| 5644 | and synthesis_md is not None |
| 5645 | and not args.deep_research |
| 5646 | ): |
| 5647 | cached = _load_last_report_cache( |
| 5648 | topic, |
| 5649 | ttl_seconds=_report_cache_ttl_seconds(config), |
| 5650 | x_envelope_sha256=_envelope_digest( |
| 5651 | x_posts_envelope, comp_plan, reddit_threads_envelope, shortform_urls_envelope, |
| 5652 | ), |
| 5653 | research_options=research_options, |
| 5654 | requested_window=requested_window, |
| 5655 | use_cached_envelopes=args.cached_report, |
| 5656 | ) |
| 5657 | if cached is not None: |
| 5658 | cached_report = cached.report |
| 5659 | cached_entity_reports = cached.entity_reports |
| 5660 | cache_path = cached.path |
| 5661 | sys.stderr.write( |
| 5662 | f"[last30days] Reusing cached report data from {cache_path}\n" |
| 5663 | ) |
| 5664 | sys.stderr.flush() |
| 5665 | if not args.cached_report and _freshness_enabled(args, config): |
| 5666 | _verify_report_set( |
| 5667 | cached_report, |
| 5668 | cached_entity_reports, |
| 5669 | allow_network=not args.mock, |
| 5670 | ) |
| 5671 | _update_cached_freshness(cached) |
| 5672 | return _render_save_and_print( |
| 5673 | args, cached_report, cached_entity_reports, synthesis_md, config |
| 5674 | ) |
| 5675 | if args.cached_report: |
| 5676 | sys.stderr.write("[last30days] No matching cached report data; rerun research with recreated plans before exporting HTML.\n") |
| 5677 | return 2 |
| 5678 | sys.stderr.write( |
| 5679 | "[last30days] No matching cached report data for " |
| 5680 | "--emit=html --synthesis-file; running fresh research.\n" |
| 5681 | ) |
| 5682 | sys.stderr.flush() |
| 5683 | |
| 5684 | # LAW 7: an agent host that skipped --plan stops before live diagnostics, |
| 5685 | # auto-resolve, the internal planner, or any source retrieval can spend. |
| 5686 | law7_exit = _law7_host_plan_gate(args, topic) |
| 5687 | if law7_exit is not None: |
| 5688 | return law7_exit |
| 5689 | |
| 5690 | diag = pipeline.diagnose( |
| 5691 | pipeline.with_plan_source_omissions(config, external_plan), |
| 5692 | requested_sources, safe=args.mock, |
| 5693 | x_envelope=x_posts_envelope is not None, |
| 5694 | probe_x=( |
| 5695 | (external_plan is None or pipeline._external_plan_names_source(external_plan, "x")) |
| 5696 | and not (args.hiring_signals and requested_sources is None) |
| 5697 | and not any(entry.get("_x_envelope") for entry in comp_plan.values()) |
| 5698 | ), |
| 5699 | ) |
| 5700 | if args.deep_research: |
| 5701 | from lib import perplexity |
| 5702 | |
| 5703 | # Deep Research defaults to a 600s Perplexity wait; anchor the command |
| 5704 | # finalization cutoff past that timeout plus a finalization reserve. |
| 5705 | research_finalization_deadline = ( |
| 5706 | command_started |
| 5707 | + perplexity.deep_timeout_seconds(config) |
| 5708 | + pipeline.DEEP_RESEARCH_RECEIPT_SECONDS |
| 5709 | + pipeline.FINALIZATION_WORK_CUTOFF_SECONDS |
| 5710 | ) |
| 5711 | else: |
| 5712 | research_finalization_deadline = finalization_deadline |
| 5713 | config = {**config, "_finalization_deadline": research_finalization_deadline} |
| 5714 | |
| 5715 | # Competitor sub-runs shallow-copy this config. The shared object makes the |
| 5716 | # paid Perplexity cap command-wide and thread-safe across that fanout. Keep |
| 5717 | # this runtime-only object out of the safe diagnose configuration contract. |
| 5718 | config["_perplexity_paid_budget"] = pipeline.PaidSourceBudget() |
| 5719 | |
| 5720 | progress = ui.ProgressDisplay(topic, show_banner=True) |
| 5721 | progress.start_processing() |
| 5722 | |
| 5723 | depth = "deep" if args.deep else "quick" if args.quick else "default" |
| 5724 | # CLI overrides for the depth profile's result caps (issue #716). Stashed on |
| 5725 | # config so pipeline.run() can apply them without widening its signature; the |
| 5726 | # comparison path inherits them via `entity_config = dict(config)`. |
| 5727 | if args.max_results is not None: |
| 5728 | config["_max_results"] = args.max_results |
| 5729 | if args.max_per_source is not None: |
| 5730 | config["_max_per_source"] = args.max_per_source |
| 5731 | if args.max_source_fetches is not None: |
| 5732 | config["_max_source_fetches"] = args.max_source_fetches |
| 5733 | try: |
| 5734 | x_related = [h.strip() for h in args.x_related.split(",") if h.strip()] if args.x_related else None |
| 5735 | subreddits = [s.strip().removeprefix("r/") for s in args.subreddits.split(",") if s.strip()] if args.subreddits else None |
| 5736 | dedicated_subreddits = [s.strip().removeprefix("r/") for s in args.dedicated_subreddits.split(",") if s.strip()] if args.dedicated_subreddits else None |
| 5737 | tiktok_hashtags = [h.strip().lstrip("#") for h in args.tiktok_hashtags.split(",") if h.strip()] if args.tiktok_hashtags else None |
| 5738 | tiktok_creators = [c.strip().lstrip("@") for c in args.tiktok_creators.split(",") if c.strip()] if args.tiktok_creators else None |
| 5739 | ig_creators = [c.strip().lstrip("@") for c in args.ig_creators.split(",") if c.strip()] if args.ig_creators else None |
| 5740 | # Auto-resolve: use web search to discover subreddits/handles before planning. |
| 5741 | # This is the engine-side equivalent of SKILL.md Steps 0.55/0.75 for platforms |
| 5742 | # without WebSearch (OpenClaw, Codex, raw CLI). |
| 5743 | repos_from_auto_resolve = False |
| 5744 | trustpilot_domain_is_hint = False |
| 5745 | x_handle_from_auto = False |
| 5746 | github_user_from_auto = False |
| 5747 | auto_official_site = "" |
| 5748 | # Resolve automatically for entity-shaped topics even without the flag. |
| 5749 | # A person or company topic whose handle the user did not supply is the |
| 5750 | # case where first-party evidence is hardest to protect: the handle is |
| 5751 | # absent from the topic and may never appear in retrieved mentions, so |
| 5752 | # nothing downstream can identify the subject's own posts. One web |
| 5753 | # search closes that. If it returns nothing, pipeline.run skips the X |
| 5754 | # relevance floor entirely — a noisier report beats losing evidence. |
| 5755 | # Skipped when a handle was already supplied, when an external plan |
| 5756 | # owns resolution, or in mock runs. |
| 5757 | # A person run resolves who the person is before the X-handle gate: |
| 5758 | # a handle on their profile or bio page changes which lanes run. |
| 5759 | person_ctx = _person_resolve_step(args, topic, config, requested_sources) |
| 5760 | if person_ctx is not None: |
| 5761 | config["_person"] = person_ctx |
| 5762 | |
| 5763 | auto_resolve_topic = topic |
| 5764 | if args.competitors_list is None and (args.competitors is None or comp_plan): |
| 5765 | from lib import planner as _planner |
| 5766 | vs_entities = _planner._comparison_entities(topic, uncapped=True) |
| 5767 | if len(vs_entities) >= 2: |
| 5768 | auto_resolve_topic = vs_entities[0] |
| 5769 | if ( |
| 5770 | not args.auto_resolve |
| 5771 | and not external_plan |
| 5772 | and not args.x_handle |
| 5773 | and not args.mock |
| 5774 | and _looks_like_entity_topic(auto_resolve_topic) |
| 5775 | ): |
| 5776 | args.auto_resolve = True |
| 5777 | sys.stderr.write( |
| 5778 | "[AutoResolve] entity-shaped topic with no --x-handle; " |
| 5779 | "resolving the subject's handle so its own posts are not pruned\n" |
| 5780 | ) |
| 5781 | |
| 5782 | if args.auto_resolve and not external_plan: |
| 5783 | from lib import resolve |
| 5784 | resolution = resolve.auto_resolve(auto_resolve_topic, config) |
| 5785 | if resolution.get("subreddits") and not subreddits: |
| 5786 | subreddits = resolution["subreddits"] |
| 5787 | sys.stderr.write(f"[AutoResolve] Subreddits: {', '.join(subreddits)}\n") |
| 5788 | # A person run takes handles only from the host or the person's own |
| 5789 | # profile and bio page; one picked by counting mentions may be a |
| 5790 | # namesake's. |
| 5791 | if resolution.get("x_handle") and not args.x_handle and person_ctx is None: |
| 5792 | args.x_handle = resolution["x_handle"] |
| 5793 | x_handle_from_auto = True |
| 5794 | sys.stderr.write(f"[AutoResolve] X handle: @{args.x_handle}\n") |
| 5795 | # Empty x_handle is intentional: do not invent a lexical stand-in. |
| 5796 | # pipeline.run treats an unidentified subject as "skip the X floor". |
| 5797 | if resolution.get("github_user") and not args.github_user and person_ctx is None: |
| 5798 | args.github_user = resolution["github_user"] |
| 5799 | github_user_from_auto = True |
| 5800 | sys.stderr.write(f"[AutoResolve] GitHub user: @{args.github_user}\n") |
| 5801 | if resolution.get("github_repos") and not args.github_repo: |
| 5802 | args.github_repo = ",".join(resolution["github_repos"]) |
| 5803 | # auto_resolve already canonicalized via canonicalize_github_repos(cap=5); |
| 5804 | # mark so we don't re-canonicalize below and clobber its relevance order. |
| 5805 | repos_from_auto_resolve = True |
| 5806 | sys.stderr.write(f"[AutoResolve] GitHub repos: {args.github_repo}\n") |
| 5807 | if resolution.get("trustpilot_domain") and not args.trustpilot_domain: |
| 5808 | # Hint provenance matters: only user-set flags are verbatim-final; |
| 5809 | # a resolved hint retries via the CLI search when it misses. |
| 5810 | args.trustpilot_domain = resolution["trustpilot_domain"] |
| 5811 | trustpilot_domain_is_hint = True |
| 5812 | sys.stderr.write(f"[AutoResolve] Trustpilot domain: {args.trustpilot_domain} (hint)\n") |
| 5813 | if resolution.get("trustpilot_domain") and person_ctx is None: |
| 5814 | # The brand's review-page domain is its own site. A person run |
| 5815 | # skips it: a host whose label matches the bare name may be a |
| 5816 | # namesake's site. |
| 5817 | auto_official_site = resolution["trustpilot_domain"] |
| 5818 | if resolution.get("context"): |
| 5819 | # Inject context into external_plan metadata for the planner to use |
| 5820 | if not external_plan: |
| 5821 | external_plan = None # planner will use its own, but with context |
| 5822 | # Store context for the planner prompt injection |
| 5823 | config["_auto_resolve_context"] = resolution["context"] |
| 5824 | sys.stderr.write(f"[AutoResolve] Context: {resolution['context'][:80]}...\n") |
| 5825 | |
| 5826 | # The brand's homepage links its own X and GitHub accounts: the most |
| 5827 | # reliable first-party source, and keyless. A user flag wins over the |
| 5828 | # homepage; the homepage wins over a handle auto-resolve picked by |
| 5829 | # counting mentions in search results. |
| 5830 | official_site = (args.official_site or "").strip() or auto_official_site |
| 5831 | if official_site and not args.mock: |
| 5832 | from lib import resolve as resolve_lib |
| 5833 | socials = resolve_lib.official_site_socials(official_site) |
| 5834 | if socials["x_handle"] and (not args.x_handle or x_handle_from_auto): |
| 5835 | args.x_handle = socials["x_handle"] |
| 5836 | sys.stderr.write(f"[Resolve] X handle from {official_site}: @{args.x_handle}\n") |
| 5837 | if socials["github_user"] and (not args.github_user or github_user_from_auto): |
| 5838 | args.github_user = socials["github_user"] |
| 5839 | sys.stderr.write(f"[Resolve] GitHub user from {official_site}: @{args.github_user}\n") |
| 5840 | if args.no_x_handle and not args.x_handle: |
| 5841 | sys.stderr.write(f"[Resolve] No X handle: {args.no_x_handle.strip()}\n") |
| 5842 | x_decision_signal = _x_handle_decision_signal( |
| 5843 | args, topic, external_plan, diag.get("available_sources") or [], |
| 5844 | ) |
| 5845 | if x_decision_signal: |
| 5846 | sys.stderr.write(_x_handle_decision_message(x_decision_signal)) |
| 5847 | raise SystemExit(X_HANDLE_DECISION_EXIT) |
| 5848 | |
| 5849 | github_user = args.github_user.lstrip("@").lower() if args.github_user else None |
| 5850 | github_repos = [r.strip() for r in args.github_repo.split(",") if r.strip() and "/" in r.strip()] if args.github_repo else None |
| 5851 | trustpilot_domain = args.trustpilot_domain.strip() if args.trustpilot_domain else None |
| 5852 | |
| 5853 | comp_enabled, comp_count, comp_explicit = resolve_competitors_args(args) |
| 5854 | # comp_plan was parsed, and its per-entity envelopes validated, before |
| 5855 | # the report-cache lookup above. |
| 5856 | |
| 5857 | # Plan-level trustpilot_domain pins are the same user intent as the CLI |
| 5858 | # flag (already activated above). Auto-resolve hints must not activate. |
| 5859 | if plan_has_explicit_trustpilot_domain(comp_plan): |
| 5860 | requested_sources = activate_trustpilot_for_explicit_domain( |
| 5861 | config, |
| 5862 | requested_sources, |
| 5863 | reason="competitors-plan trustpilot_domain", |
| 5864 | ) |
| 5865 | |
| 5866 | # Only canonicalize when repos came from a user-supplied --github-repo flag. |
| 5867 | # When repos_from_auto_resolve is True, auto_resolve already ran |
| 5868 | # canonicalize_github_repos(cap=5) and ranked by relevance; re-running here |
| 5869 | # with cap=None can re-sort by topic-slug match and lose that ordering. |
| 5870 | if github_repos and not repos_from_auto_resolve: |
| 5871 | from lib import resolve as resolve_lib |
| 5872 | original_github_repos = github_repos[:] |
| 5873 | github_repos = resolve_lib.canonicalize_github_repos(topic, github_repos, cap=None) |
| 5874 | if github_repos != original_github_repos: |
| 5875 | sys.stderr.write( |
| 5876 | "[GitHub] Canonicalized repos: " |
| 5877 | f"{','.join(original_github_repos)} -> {','.join(github_repos)}\n" |
| 5878 | ) |
| 5879 | |
| 5880 | # Polymarket disambiguation: if user passed --polymarket-keywords, |
| 5881 | # store on config so the polymarket adapter can filter matches. |
| 5882 | if args.polymarket_keywords: |
| 5883 | keywords = [ |
| 5884 | k.strip().lower() |
| 5885 | for k in args.polymarket_keywords.split(",") |
| 5886 | if k.strip() |
| 5887 | ] |
| 5888 | if keywords: |
| 5889 | config["_polymarket_keywords"] = keywords |
| 5890 | |
| 5891 | # Product keyword for the amazon source. Carried on config rather than |
| 5892 | # threaded through the run signature (the _polymarket_keywords idiom): |
| 5893 | # it is one optional string consumed in exactly two places. |
| 5894 | if getattr(args, "amazon_query", None): |
| 5895 | config["_amazon_query"] = args.amazon_query.strip() |
| 5896 | # Unlike --trustpilot-domain, this flag deliberately does NOT |
| 5897 | # auto-activate its source: the lane spends metered credits, so |
| 5898 | # turning it on stays an explicit request. But silence is the |
| 5899 | # wrong failure mode -- a model that resolves the keyword and |
| 5900 | # forgets the --search token would otherwise get no signal at |
| 5901 | # all that the flag did nothing. |
| 5902 | _amazon_requested = ( |
| 5903 | (requested_sources and "amazon" in requested_sources) |
| 5904 | or "amazon" in str(config.get("INCLUDE_SOURCES") or "").lower() |
| 5905 | ) |
| 5906 | if not _amazon_requested: |
| 5907 | sys.stderr.write( |
| 5908 | "[Amazon] --amazon-query was set but the amazon source was not " |
| 5909 | "requested; add it to --search (e.g. --search reddit,x,amazon) " |
| 5910 | "or set INCLUDE_SOURCES=amazon. Ignoring the keyword.\n" |
| 5911 | ) |
| 5912 | |
| 5913 | # Advertiser page override for the meta_ads source. Same shape as |
| 5914 | # --amazon-query (config-carried, warn-not-activate) and for the same |
| 5915 | # reason: the lane spends metered credits per call. |
| 5916 | if getattr(args, "meta_ads_page", None): |
| 5917 | page_id = parse_meta_ads_page(args.meta_ads_page) |
| 5918 | if not page_id: |
| 5919 | sys.stderr.write( |
| 5920 | "[Meta Ads] --meta-ads-page must be a numeric Ad Library page id " |
| 5921 | "or an Ad Library URL containing view_all_page_id; a facebook.com " |
| 5922 | "vanity URL is not a page id. Ignoring the override.\n" |
| 5923 | ) |
| 5924 | else: |
| 5925 | config["_meta_ads_page"] = page_id |
| 5926 | _meta_ads_requested = ( |
| 5927 | (requested_sources and "meta_ads" in requested_sources) |
| 5928 | or "meta_ads" in str(config.get("INCLUDE_SOURCES") or "").lower() |
| 5929 | ) |
| 5930 | if not _meta_ads_requested: |
| 5931 | sys.stderr.write( |
| 5932 | "[Meta Ads] --meta-ads-page was set but the meta_ads source " |
| 5933 | "was not requested; add it to --search (e.g. --search " |
| 5934 | "reddit,x,meta_ads) or set INCLUDE_SOURCES=meta_ads. " |
| 5935 | "Ignoring the page.\n" |
| 5936 | ) |
| 5937 | |
| 5938 | # vs-mode / plan routing: split a vs-topic into main + peers unless |
| 5939 | # discover-N or an explicit --competitors-list already decided who runs. |
| 5940 | topic, comp_enabled, comp_count, comp_explicit = apply_vs_competitor_routing( |
| 5941 | topic, |
| 5942 | competitors_flag=args.competitors, |
| 5943 | comp_enabled=comp_enabled, |
| 5944 | comp_count=comp_count, |
| 5945 | comp_explicit=comp_explicit, |
| 5946 | comp_plan=comp_plan, |
| 5947 | ) |
| 5948 | # Which company the topic names, from Wikidata. Like the homepage |
| 5949 | # lookup above it needs no key and does not depend on who planned the |
| 5950 | # run, so it happens with or without a host plan. Each entity of a |
| 5951 | # comparison is resolved on its own, after the split. |
| 5952 | # ``--ticker`` is the host's own answer for the main topic. Passed, it |
| 5953 | # is the only ticker source, checked against Yahoo after the run. |
| 5954 | host_tickers = ( |
| 5955 | yahoo_finance.parse_host_tickers(args.ticker) |
| 5956 | if (args.ticker or "").strip() and not args.mock else None |
| 5957 | ) |
| 5958 | patent_lane_wanted = _patent_lane_wanted( |
| 5959 | comparison=comp_enabled, mock=args.mock, hiring_signals=args.hiring_signals, |
| 5960 | depth=depth, config=config, |
| 5961 | ) |
| 5962 | main_company = _resolved_company( |
| 5963 | topic, mock=args.mock, config=config, host_ticker=host_tickers is not None, |
| 5964 | patent_lane=patent_lane_wanted, |
| 5965 | ) |
| 5966 | # The jobs lane reads the company from here; each comparison peer |
| 5967 | # replaces it with its own. |
| 5968 | host_companies = _host_companies(args.company) |
| 5969 | host_names = [company["name"] for company in host_companies] |
| 5970 | # The company's patent filings over the run's own window, fetched |
| 5971 | # beside the pipeline and collected when it returns. |
| 5972 | patent_lane = None |
| 5973 | if patent_lane_wanted: |
| 5974 | patent_lane = patents.start( |
| 5975 | _company_for_patents(main_company, host_names), |
| 5976 | *dates.get_date_range(args.lookback_days, as_of_date=args.as_of_date), |
| 5977 | config, |
| 5978 | ) |
| 5979 | config["_company"] = _company_for_jobs( |
| 5980 | main_company, host_tickers, topic, |
| 5981 | official_site=official_site, host_names=host_names, |
| 5982 | host_sites=( |
| 5983 | {} if main_company.get("company") |
| 5984 | else _host_company_sites(host_companies, mock=args.mock, config=config) |
| 5985 | ), |
| 5986 | ) |
| 5987 | # What makes the run about a company: with any of it, a host plan |
| 5988 | # that does not name the jobs lane gets it on its primary subquery. |
| 5989 | config["_company_signal"] = _company_signal( |
| 5990 | main_company, host_tickers, official_site, host_names, |
| 5991 | jobs_board=args.jobs_board or "", |
| 5992 | ) |
| 5993 | if (args.jobs_board or "").strip(): |
| 5994 | # The board URL the host found by web search; the jobs lane reads |
| 5995 | # it first and checks whose board it is. |
| 5996 | config["_jobs_board"] = args.jobs_board.strip() |
| 5997 | if comp_enabled: |
| 5998 | config["_perplexity_paid_budget"] = pipeline.PaidSourceBudget( |
| 5999 | owner=topic, |
| 6000 | ) |
| 6001 | |
| 6002 | # Plan alone with zero peers (empty/invalid JSON object, or all entries |
| 6003 | # skipped) must not fall through to discover-N with a misleading abort. |
| 6004 | if ( |
| 6005 | comp_enabled |
| 6006 | and not comp_explicit |
| 6007 | and args.competitors is None |
| 6008 | and args.competitors_plan |
| 6009 | ): |
| 6010 | sys.stderr.write( |
| 6011 | "[Competitors] --competitors-plan has no usable peer entries " |
| 6012 | "(and the topic is not a vs-comparison). Pass a non-empty plan, " |
| 6013 | "a vs-topic, --competitors-list, or --competitors N.\n" |
| 6014 | ) |
| 6015 | return 2 |
| 6016 | |
| 6017 | # Dedicated subs ride the config dict (already threaded to every source |
| 6018 | # fetch) so the keyless Reddit path can pull them floor-exempt without |
| 6019 | # widening pipeline.run / _retrieve_stream signatures. |
| 6020 | if dedicated_subreddits: |
| 6021 | config["_dedicated_subreddits"] = dedicated_subreddits |
| 6022 | |
| 6023 | def _main_runner(run_config: dict[str, object] | None = None) -> schema.Report: |
| 6024 | main_config = dict(config if run_config is None else run_config) |
| 6025 | r = pipeline.run( |
| 6026 | topic=topic, |
| 6027 | config=main_config, |
| 6028 | depth=depth, |
| 6029 | requested_sources=requested_sources, |
| 6030 | mock=args.mock, |
| 6031 | x_handle=args.x_handle, |
| 6032 | x_related=x_related, |
| 6033 | web_backend=args.web_backend, |
| 6034 | external_plan=external_plan, |
| 6035 | subreddits=subreddits, |
| 6036 | tiktok_hashtags=tiktok_hashtags, |
| 6037 | tiktok_creators=tiktok_creators, |
| 6038 | ig_creators=ig_creators, |
| 6039 | lookback_days=args.lookback_days, |
| 6040 | as_of_date=args.as_of_date, |
| 6041 | github_user=github_user, |
| 6042 | github_repos=github_repos, |
| 6043 | trustpilot_domain=trustpilot_domain, |
| 6044 | trustpilot_domain_is_hint=trustpilot_domain_is_hint, |
| 6045 | internal_subrun=comp_enabled, |
| 6046 | hiring_signals_mode=args.hiring_signals, |
| 6047 | save_dir=args.save_dir, |
| 6048 | corpus_dirs=args.corpus, |
| 6049 | corpus_all_time=args.corpus_all_time, |
| 6050 | x_posts=( |
| 6051 | comp_plan.get(topic.strip().lower(), {}).get("_x_envelope") |
| 6052 | if comp_enabled else x_posts_envelope |
| 6053 | ), |
| 6054 | reddit_threads=None if comp_enabled else reddit_threads_envelope, |
| 6055 | shortform_urls=None if comp_enabled else shortform_urls_envelope, |
| 6056 | ) |
| 6057 | patents.collect(patent_lane, r) |
| 6058 | r.artifacts["resolved"] = { |
| 6059 | "entity": topic, |
| 6060 | "x_handle": (args.x_handle or "").lstrip("@"), |
| 6061 | "subreddits": list(subreddits or []), |
| 6062 | "github_user": (github_user or ""), |
| 6063 | "github_repos": list(github_repos or []), |
| 6064 | "trustpilot_domain": (trustpilot_domain or ""), |
| 6065 | "context": main_config.get("_auto_resolve_context", "") or "", |
| 6066 | **main_company, |
| 6067 | } |
| 6068 | # The share-price window of a listed company. A mock run resolved |
| 6069 | # no company, so it never reaches the price CLI, and neither does |
| 6070 | # a run with EXCLUDE_SOURCES=yahoo_finance. |
| 6071 | if host_tickers is None: |
| 6072 | yahoo_finance.attach_market_data(r, main_company, main_config) |
| 6073 | return r |
| 6074 | checked = yahoo_finance.attach_host_tickers(r, host_tickers, main_config) |
| 6075 | # The company Wikidata named stays; the host's fills an empty one. |
| 6076 | host_company = checked.pop("company", "") |
| 6077 | r.artifacts["resolved"].update(checked) |
| 6078 | if host_company: |
| 6079 | r.artifacts["resolved"].setdefault("company", host_company) |
| 6080 | if checked.get("tickers"): |
| 6081 | sys.stderr.write( |
| 6082 | f"[Resolve] {topic}: ticker {', '.join(checked['tickers'])} (host search)\n" |
| 6083 | ) |
| 6084 | return r |
| 6085 | |
| 6086 | if comp_enabled: |
| 6087 | from lib import competitors as competitors_mod |
| 6088 | from lib import fanout, resolve as resolve_mod |
| 6089 | |
| 6090 | peers_auto_discovered = not comp_explicit |
| 6091 | if comp_explicit: |
| 6092 | discovered = comp_explicit |
| 6093 | else: |
| 6094 | if not resolve_mod._has_backend(config) and not args.mock: |
| 6095 | sys.stderr.write( |
| 6096 | "[Competitors] Cannot auto-discover peers without help.\n" |
| 6097 | "\n" |
| 6098 | "RECOMMENDED PATH (hosting reasoning models — Claude Code, Codex, " |
| 6099 | "Hermes, Gemini, any agent with a WebSearch tool): YOU have " |
| 6100 | "WebSearch. Use it to run full Step 0.55 per entity, then invoke " |
| 6101 | "the engine with a vs-topic plus --competitors-plan:\n" |
| 6102 | " 1. WebSearch for '{topic} competitors' or '{topic} alternatives'.\n" |
| 6103 | " 2. For each peer, WebSearch for handles/subs/github (Step 0.55).\n" |
| 6104 | " 3. Re-invoke: /last30days '{topic} vs {peer1} vs {peer2}' " |
| 6105 | "--competitors-plan '{\"Peer1\":{\"x_handle\":\"h1\",\"subreddits\":" |
| 6106 | "[\"s1\"],...},\"Peer2\":{...}}'.\n" |
| 6107 | "See the skill's references/competitors.md for the full protocol.\n" |
| 6108 | "\n" |
| 6109 | "HEADLESS / CRON PATH (no hosting model available): set " |
| 6110 | "BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / PARALLEL_API_KEY " |
| 6111 | "and re-run.\n" |
| 6112 | "\n" |
| 6113 | "MINIMUM ESCAPE HATCH: pass --competitors-list 'A,B,C' to skip " |
| 6114 | "discovery. Without --competitors-plan, peer sub-runs fall back to " |
| 6115 | "planner defaults and produce visibly thinner data than the main.\n" |
| 6116 | ) |
| 6117 | return 2 |
| 6118 | discovered = competitors_mod.discover_competitors( |
| 6119 | topic, comp_count, config, lookback_days=args.lookback_days, |
| 6120 | is_company=( |
| 6121 | not main_company.get("company_via_person") |
| 6122 | and main_company.get("company_peer_discovery") |
| 6123 | != company_resolve.COMPANY_PEER_KEYWORD |
| 6124 | and bool( |
| 6125 | main_company.get("company") |
| 6126 | or config.get("_company_signal") |
| 6127 | ) |
| 6128 | ), |
| 6129 | ) |
| 6130 | if not discovered: |
| 6131 | sys.stderr.write( |
| 6132 | f"[Competitors] No peers discovered for {topic!r}; aborting " |
| 6133 | "comparison run. Pass --competitors-list to override.\n" |
| 6134 | ) |
| 6135 | return 2 |
| 6136 | |
| 6137 | # run_competitor_fanout keys its results by label, so two |
| 6138 | # submissions sharing one collapse to a single report while the |
| 6139 | # returned list still carries two entries. That yields a |
| 6140 | # comparison of an entity against itself, and it hides a failed |
| 6141 | # main topic from the survivor check below: the duplicate peer's |
| 6142 | # report answers for the label the main run was supposed to fill. |
| 6143 | distinct_peers: list[str] = [] |
| 6144 | claimed_labels = {comparison_label_key(topic)} |
| 6145 | for peer in discovered: |
| 6146 | key = comparison_label_key(peer) |
| 6147 | if key in claimed_labels: |
| 6148 | sys.stderr.write( |
| 6149 | f"[Competitors] Dropping {peer!r}: duplicates the main " |
| 6150 | "topic or an earlier peer.\n" |
| 6151 | ) |
| 6152 | continue |
| 6153 | claimed_labels.add(key) |
| 6154 | distinct_peers.append(peer) |
| 6155 | if not distinct_peers: |
| 6156 | sys.stderr.write( |
| 6157 | f"[Competitors] No peer distinct from {topic!r} remains; " |
| 6158 | "there is nothing to compare against. Pass " |
| 6159 | "--competitors-list with distinct entities.\n" |
| 6160 | ) |
| 6161 | return 2 |
| 6162 | discovered = distinct_peers |
| 6163 | config["_comparison_entity_count"] = 1 + len(discovered) |
| 6164 | # Each entity's jobs lane leaves every entity's name out of the |
| 6165 | # story terms it searches its board for. |
| 6166 | config["_comparison_entities"] = [topic, *discovered] |
| 6167 | # Snapshot an immutable-by-convention base dict before fan-out |
| 6168 | # spawns worker threads so no thread iterates or mutates a shared |
| 6169 | # config concurrently. |
| 6170 | peer_base_config = dict(config) |
| 6171 | main_run_config = dict(peer_base_config) |
| 6172 | |
| 6173 | sys.stderr.write( |
| 6174 | f"[Competitors] Comparing: {topic} vs " + " vs ".join(discovered) + "\n" |
| 6175 | ) |
| 6176 | |
| 6177 | def _competitor_runner(entity: str) -> schema.Report: |
| 6178 | # Resolution belongs to each entity, not the shared command. |
| 6179 | entity_config = dict(peer_base_config) |
| 6180 | entity_config.pop("_auto_resolve_context", None) |
| 6181 | # The main topic's company flags and run-scoped transient keys |
| 6182 | # are not a peer's. |
| 6183 | entity_config.pop("_company", None) |
| 6184 | entity_config.pop("_company_signal", None) |
| 6185 | entity_config.pop("_jobs_board", None) |
| 6186 | entity_config.pop("_jobs_story_terms", None) |
| 6187 | entity_config.pop("_financial_topic", None) |
| 6188 | entity_config.pop("_person", None) |
| 6189 | entity_config.pop("_x_envelope", None) |
| 6190 | entity_config.pop("_x_lane_missing", None) |
| 6191 | entity_config.pop("_reddit_envelope", None) |
| 6192 | entity_config.pop("_shortform_envelope", None) |
| 6193 | # The Amazon keyword is entity-SPECIFIC, unlike the depth caps |
| 6194 | # this shallow copy exists to inherit. Leaving the main topic's |
| 6195 | # keyword in place would search Weber SKUs for a Traeger peer, |
| 6196 | # render a rival's products as that peer's buyer evidence, and |
| 6197 | # multiply the metered spend by the number of entities. Drop it |
| 6198 | # so each peer derives its own keyword from its own topic; a |
| 6199 | # per-entity keyword can ride in the --competitors-plan entry. |
| 6200 | entity_config.pop("_amazon_query", None) |
| 6201 | # dev.to tags describe the main topic; a peer falls back to |
| 6202 | # the slug of its own name instead of a rival's tags. |
| 6203 | entity_config.pop("_devto_tags", None) |
| 6204 | # An advertiser page is per-entity state by definition: left in |
| 6205 | # place it would render one brand's ads as every peer's. |
| 6206 | entity_config.pop("_meta_ads_page", None) |
| 6207 | entity_config.pop("_dedicated_subreddits", None) |
| 6208 | # Auto-discovered peers come from external search titles (e.g. Exa), |
| 6209 | # never from user input, so an r/<name> mention in a peer title |
| 6210 | # must not grant access to private or quarantined subreddits. |
| 6211 | if peers_auto_discovered: |
| 6212 | entity_config["_reddit_named_subreddits"] = frozenset() |
| 6213 | else: |
| 6214 | entity_config.pop("_reddit_named_subreddits", None) |
| 6215 | # Polymarket keywords and hints name the main topic's subject; |
| 6216 | # a peer searches on its own name plus its own plan entry hints. |
| 6217 | entity_config.pop("_polymarket_keywords", None) |
| 6218 | entity_config.pop("_polymarket_hints", None) |
| 6219 | plan_entry = comp_plan.get(entity.strip().lower(), {}) |
| 6220 | if plan_entry.get("polymarket_hints"): |
| 6221 | entity_config["_polymarket_hints"] = plan_entry["polymarket_hints"] |
| 6222 | resolved = { |
| 6223 | "entity": entity, |
| 6224 | "x_handle": "", |
| 6225 | "subreddits": [], |
| 6226 | "github_user": "", |
| 6227 | "github_repos": [], |
| 6228 | "trustpilot_domain": "", |
| 6229 | "context": "", |
| 6230 | } |
| 6231 | # Skip engine-internal auto_resolve when the hosting model |
| 6232 | # pre-resolved via --competitors-plan (saves a redundant |
| 6233 | # round-trip and makes per-entity Step 0.55 purely |
| 6234 | # hosting-model-driven). |
| 6235 | plan_covers_fully = bool(plan_entry.get("x_handle")) and bool( |
| 6236 | plan_entry.get("subreddits") |
| 6237 | ) |
| 6238 | if ( |
| 6239 | not args.mock |
| 6240 | and not plan_covers_fully |
| 6241 | and resolve_mod._has_backend(entity_config) |
| 6242 | ): |
| 6243 | try: |
| 6244 | r = resolve_mod.auto_resolve(entity, entity_config) |
| 6245 | except Exception as exc: |
| 6246 | sys.stderr.write( |
| 6247 | f"[Competitors] auto_resolve failed for {entity!r}: " |
| 6248 | f"{type(exc).__name__}: {exc}\n" |
| 6249 | ) |
| 6250 | r = {} |
| 6251 | resolved["x_handle"] = r.get("x_handle", "") or "" |
| 6252 | resolved["subreddits"] = list(r.get("subreddits") or []) |
| 6253 | resolved["github_user"] = r.get("github_user", "") or "" |
| 6254 | resolved["github_repos"] = list(r.get("github_repos") or []) |
| 6255 | resolved["trustpilot_domain"] = r.get("trustpilot_domain", "") or "" |
| 6256 | resolved["context"] = r.get("context", "") or "" |
| 6257 | kwargs = subrun_kwargs_for(entity, plan_entry, resolved=resolved) |
| 6258 | # Record effective per-entity targeting for the Resolved block. |
| 6259 | resolved_effective = { |
| 6260 | "entity": entity, |
| 6261 | "x_handle": kwargs["x_handle"] or "", |
| 6262 | "subreddits": kwargs["subreddits"] or [], |
| 6263 | "github_user": kwargs["github_user"] or "", |
| 6264 | "github_repos": kwargs["github_repos"] or [], |
| 6265 | "trustpilot_domain": kwargs["trustpilot_domain"] or "", |
| 6266 | "context": kwargs["_context"], |
| 6267 | **_resolved_company(entity, mock=args.mock, config=entity_config), |
| 6268 | } |
| 6269 | entity_config["_company"] = resolved_effective |
| 6270 | if kwargs["_context"]: |
| 6271 | entity_config["_auto_resolve_context"] = kwargs["_context"] |
| 6272 | sys.stderr.write( |
| 6273 | f"[Competitors] {entity}: " |
| 6274 | f"x=@{resolved_effective['x_handle'] or '-'} " |
| 6275 | f"subs={len(resolved_effective['subreddits'])} " |
| 6276 | f"gh={resolved_effective['github_user'] or '-'} " |
| 6277 | f"({'plan' if plan_entry else 'auto'})\n" |
| 6278 | ) |
| 6279 | report = pipeline.run( |
| 6280 | topic=entity, |
| 6281 | config=entity_config, |
| 6282 | depth=depth, |
| 6283 | requested_sources=requested_sources, |
| 6284 | mock=args.mock, |
| 6285 | x_handle=kwargs["x_handle"], |
| 6286 | x_related=kwargs["x_related"], |
| 6287 | subreddits=kwargs["subreddits"], |
| 6288 | github_user=kwargs["github_user"], |
| 6289 | github_repos=kwargs["github_repos"], |
| 6290 | trustpilot_domain=kwargs["trustpilot_domain"], |
| 6291 | trustpilot_domain_is_hint=kwargs["_trustpilot_domain_is_hint"], |
| 6292 | web_backend=args.web_backend, |
| 6293 | lookback_days=args.lookback_days, |
| 6294 | as_of_date=args.as_of_date, |
| 6295 | hiring_signals_mode=args.hiring_signals, |
| 6296 | internal_subrun=True, |
| 6297 | save_dir=args.save_dir, |
| 6298 | corpus_dirs=args.corpus, |
| 6299 | corpus_all_time=args.corpus_all_time, |
| 6300 | x_posts=plan_entry.get("_x_envelope"), |
| 6301 | ) |
| 6302 | report.artifacts["resolved"] = resolved_effective |
| 6303 | yahoo_finance.attach_market_data(report, resolved_effective, entity_config) |
| 6304 | return report |
| 6305 | |
| 6306 | entity_reports = fanout.run_competitor_fanout( |
| 6307 | main_topic=topic, |
| 6308 | main_runner=lambda: _main_runner(main_run_config), |
| 6309 | competitors=discovered, |
| 6310 | competitor_runner=_competitor_runner, |
| 6311 | ) |
| 6312 | # run_competitor_fanout drops a failed sub-run from the list, and |
| 6313 | # the render takes entity_reports[0] as the comparison's subject. |
| 6314 | # Without this check, a main topic that raised while >=2 peers |
| 6315 | # succeeded silently promoted a competitor to be the subject: the |
| 6316 | # report was headed by that peer, saved under its slug, and the |
| 6317 | # topic the user actually asked about went unmentioned. |
| 6318 | survived = {label for label, _ in entity_reports} |
| 6319 | dropped = [ |
| 6320 | label for label in (topic, *discovered) if label not in survived |
| 6321 | ] |
| 6322 | if topic not in survived: |
| 6323 | progress.end_processing() |
| 6324 | sys.stderr.write( |
| 6325 | f"[Competitors] The main topic {topic!r} failed; " |
| 6326 | f"{len(entity_reports)} competitor sub-run(s) survived. " |
| 6327 | "Refusing to render a comparison headed by a competitor. " |
| 6328 | "Check the warnings above.\n" |
| 6329 | ) |
| 6330 | return 1 |
| 6331 | if len(entity_reports) < 2: |
| 6332 | progress.end_processing() |
| 6333 | sys.stderr.write( |
| 6334 | f"[Competitors] Fewer than 2 sub-runs survived ({len(entity_reports)}); " |
| 6335 | "cannot render a comparison. Re-run without --competitors or check the " |
| 6336 | "warnings above.\n" |
| 6337 | ) |
| 6338 | return 1 |
| 6339 | report = entity_reports[0][1] |
| 6340 | if dropped: |
| 6341 | # A narrower comparison than the user asked for is a result |
| 6342 | # they need to see, not a silent substitution. |
| 6343 | report.warnings.append( |
| 6344 | "Comparison is incomplete: " |
| 6345 | f"{len(dropped)} of {len(discovered) + 1} entities failed and " |
| 6346 | f"were dropped ({', '.join(dropped)})." |
| 6347 | ) |
| 6348 | else: |
| 6349 | entity_reports = None |
| 6350 | report = _main_runner() |
| 6351 | except pipeline.NoRequestedSourceAvailable as exc: |
| 6352 | # A setup problem, not a crash: say what to do instead of a traceback |
| 6353 | progress.end_processing() |
| 6354 | sys.stderr.write(f"{exc}\n") |
| 6355 | return 2 |
| 6356 | except Exception as exc: |
| 6357 | progress.end_processing() |
| 6358 | progress.show_error(str(exc)) |
| 6359 | raise |
| 6360 | if _freshness_enabled(args, config): |
| 6361 | _verify_report_set(report, entity_reports, allow_network=not args.mock) |
| 6362 | |
| 6363 | _show_runtime_ui( |
| 6364 | report, progress, diag, |
| 6365 | suppress_web_promo=bool(external_plan or comp_plan), |
| 6366 | ) |
| 6367 | if not args.no_research_persistence: |
| 6368 | _write_last_run( |
| 6369 | original_topic, report, entity_reports=entity_reports, |
| 6370 | x_envelope_sha256=_envelope_digest( |
| 6371 | x_posts_envelope, comp_plan, reddit_threads_envelope, shortform_urls_envelope, |
| 6372 | ), |
| 6373 | research_options=research_options, |
| 6374 | ) |
| 6375 | if _research_store_enabled(args, config): |
| 6376 | store_db = _scoped_store_db(args) |
| 6377 | reports_to_store = ( |
| 6378 | [item for _, item in entity_reports] if entity_reports else [report] |
| 6379 | ) |
| 6380 | counts = {"new": 0, "updated": 0} |
| 6381 | for current in reports_to_store: |
| 6382 | current_counts = persist_report(current, store_db=store_db) or {} |
| 6383 | counts["new"] += int(current_counts.get("new") or 0) |
| 6384 | counts["updated"] += int(current_counts.get("updated") or 0) |
| 6385 | sys.stderr.write( |
| 6386 | f"[last30days] Stored {counts['new']} new, {counts['updated']} updated findings\n" |
| 6387 | ) |
| 6388 | sys.stderr.flush() |
| 6389 | |
| 6390 | # Show quality nudge if applicable. Explicit hiring-signal runs are |
| 6391 | # intentionally jobs-focused, so generic source setup advice is noise. |
| 6392 | if not args.hiring_signals: |
| 6393 | try: |
| 6394 | from lib import quality_nudge |
| 6395 | from lib import youtube_yt as _youtube_yt |
| 6396 | research_results = _quality_research_results( |
| 6397 | report, diag, _youtube_yt.get_transcript_fetch_stats() |
| 6398 | ) |
| 6399 | quality = quality_nudge.compute_quality_score(config, research_results) |
| 6400 | if quality.get("nudge_text"): |
| 6401 | sys.stderr.write(f"\n{quality['nudge_text']}\n") |
| 6402 | sys.stderr.flush() |
| 6403 | except Exception: |
| 6404 | pass |
| 6405 | |
| 6406 | # Signal to render_compact whether pre-research flags were supplied. |
| 6407 | # Used to emit a Pre-Research Status warning when the model skipped |
| 6408 | # Step 0.5 / 0.55 and invoked the engine bare on an eligible topic. |
| 6409 | pre_research_flags_present = bool( |
| 6410 | args.x_handle |
| 6411 | or args.github_user |
| 6412 | or args.subreddits |
| 6413 | or args.plan |
| 6414 | or args.auto_resolve |
| 6415 | or args.tiktok_creators |
| 6416 | or args.ig_creators |
| 6417 | ) |
| 6418 | report.artifacts["pre_research_flags_present"] = pre_research_flags_present |
| 6419 | |
| 6420 | exit_code = _render_save_and_print(args, report, entity_reports, synthesis_md, config) |
| 6421 | if args.emit in {"compact", "md", "brief"}: |
| 6422 | x_omission = _optional_x_omission_text(diag, requested_sources) |
| 6423 | if x_omission: |
| 6424 | sys.stderr.write(f"\n{x_omission}\n") |
| 6425 | sys.stderr.flush() |
| 6426 | return exit_code |
| 6427 | |
| 6428 | |
| 6429 | if __name__ == "__main__": |
| 6430 | _install_sigterm_handler() |
| 6431 | raise SystemExit(main()) |
| 6432 |