返回 last30days-skill
trustpilot.py
根目录 / skills / last30days / scripts / lib / trustpilot.py
1 """Trustpilot brand-sentiment source for last30days.
2
3 Shells out to ``trustpilot-pp-cli`` to surface a company's TrustScore and
4 Trustpilot's own AI review summary for brand/company topics. Trustpilot has no
5 API key, but it sits behind AWS WAF: the CLI replays an ``aws-waf-token`` that
6 only a Chrome launch can harvest (``trustpilot-pp-cli auth login``) and that
7 stays replayable for about four minutes.
8
9 A research run never launches a browser on the user's machine. The CLI has no
10 no-browser mode (every fetch command harvests by itself when its session is
11 missing or stale), so this module asks ``auth status`` first, which is a local
12 read, and calls a fetch command only while the saved session is fresh.
13 Otherwise it reads the CLI's cached company record (``info <domain> --local``,
14 a local read that needs no session) and labels the data with its cache age.
15 With no usable cached record the lane is skipped quietly: one stderr line with
16 the sign-in command, and a not-attempted "no results" outcome carrying
17 ``SESSION_NEEDED``, never a failed or degraded source. ``can_run_now`` tells
18 ``--diagnose`` and doctor which of these a run would get, so the host does not
19 resolve a domain for a lane that would skip.
20
21 Activation gate: only available when ``trustpilot-pp-cli`` is on PATH.
22 ``pipeline.available_sources`` checks ``shutil.which`` before including
23 ``trustpilot``.
24
25 Default-on safety (three gates):
26 1. Brand-shape gate. The CLI is invoked only when the topic resolves to a
27 company/brand -- a domain-like token, or a short (<=2-word) capitalized
28 proper noun. Generic phrases ("AI coding agents", "agent memory") and
29 longer multi-word phrases never call the CLI, so Trustpilot stays quiet --
30 and never harvests Chrome -- on non-company topics. An explicit resolved
31 domain (``--trustpilot-domain`` or an auto-resolve hint) bypasses this
32 gate: an explicit domain is proof of brand intent.
33 2. Browser opt-out. Automated contexts (cron, CI, the eval harness) can set
34 ``LAST30DAYS_TRUSTPILOT_NO_BROWSER`` to disable the source entirely, so a
35 headless run never spawns the cookie harvest.
36 3. Graceful degradation. Any CLI failure (no Chrome, expired cookie that
37 cannot re-harvest, timeout) degrades to empty results, never an error.
38
39 Domain resolution: Trustpilot review pages are keyed by domain
40 (``www.thriftbooks.com``), not company name -- ``info ThriftBooks`` 404s.
41 Priority chain: user flag (verbatim) > auto-resolve hint (retries via search
42 on a miss) > domain token in the topic > CLI ``search`` name->domain lookup
43 (cached per topic) > cleaned topic (legacy behavior).
44
45 Session pre-flight: ``ensure_session_ready`` runs ``auth status`` before each
46 fetch command and never ``auth login``.
47 """
48
49 from __future__ import annotations
50
51 import json
52 import os
53 import re
54 import shutil
55 import threading
56 import time
57 import unicodedata
58 from datetime import datetime, timezone
59 from typing import Any, Callable, Dict, List, Optional
60
61 from . import dates, log, subproc
62 from .relevance import token_overlap_relevance
63
64
65 CLI_BIN = "trustpilot-pp-cli"
66
67 SEARCH_TIMEOUT = 75 # generous: a cold run may harvest a WAF cookie (~10s).
68
69 AUTH_STATUS_TIMEOUT = 20 # auth status is a local SQLite read; fast.
70
71 # `info <domain> --local` and `doctor-tp` read the CLI's local store only.
72 LOCAL_READ_TIMEOUT = 10
73
74 # A cached company record older than the research window is not evidence
75 # about the last 30 days, so it is not used.
76 CACHE_MAX_AGE_DAYS = 30
77
78 NO_BROWSER_ENV = "LAST30DAYS_TRUSTPILOT_NO_BROWSER"
79
80 # The source outcome when the saved session cannot be replayed.
81 SESSION_NEEDED = (
82 "Trustpilot needs a browser session, and a research run never opens a browser: "
83 "run `trustpilot-pp-cli auth login`, then run again within 3 minutes"
84 )
85 # The CLI replays a session for 4 minutes from its harvest and launches Chrome
86 # after that. A session this close to the limit could lapse during the call.
87 CLI_SESSION_SECONDS = 240
88 SESSION_MARGIN_SECONDS = 45
89
90 # Among name-matching search hits, the top hit must have this many times the
91 # runner-up's review volume to win automatically. Lookalike/squatter pages have
92 # tiny volume (ThriftBooks: 2.8M vs 130); comparable volume means genuine
93 # ambiguity, where falling back beats silently picking the wrong company.
94 DOMAIN_DOMINANCE_FACTOR = 50
95
96 # Domain-like token, e.g. "chownow.com", "nothing.tech".
97 _DOMAIN_RE = re.compile(
98 r"(?<![\w.-])(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+"
99 r"(?:com|io|co|net|org|app|ai|dev|gg|tech|shop|store)"
100 r"(?:\.[a-z]{2,63})*(?![\w-]|\.[\w-])"
101 )
102
103 # Strict hostname allowlist for explicit / resolved domains passed to the CLI.
104 # Uses \Z (not $) so trailing newlines cannot sneak past validation.
105 _STRICT_DOMAIN_RE = re.compile(
106 r"\A(?=.{1,253}\Z)"
107 r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+"
108 r"(?:[A-Za-z]{2,63}|[Xx][Nn]--[A-Za-z0-9](?:[A-Za-z0-9-]{0,57}[A-Za-z0-9])?)\Z"
109 )
110 _URL_USERINFO_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]{0,15}://)[^\s/?#]+@")
111
112
113 _INVALID_DOMAIN_ERROR = "Invalid Trustpilot domain: use a bare hostname without a scheme or path."
114
115
116 def _scrub_url_userinfo(text: str) -> str:
117 return _URL_USERINFO_RE.sub(r"\1", text) if text else text
118
119 # Keep only OS, cache/config-dir, locale, TLS, and proxy settings.
120 # Never inherit unrelated provider secrets or runtime-injection vars like NODE_OPTIONS.
121 _CHILD_ENV_ALLOWLIST = frozenset({
122 "PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA",
123 "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME",
124 "XDG_STATE_HOME", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "COMSPEC",
125 "PATHEXT", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE",
126 "TZ", "NO_COLOR", "TERM", "SSL_CERT_FILE", "SSL_CERT_DIR",
127 "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
128 })
129
130 # Generic tokens that disqualify a short capitalized phrase from being a brand.
131 _GENERIC_TOKENS = {
132 "ai", "best", "top", "vs", "review", "reviews", "guide", "tutorial",
133 "how", "what", "why", "agents", "agent", "memory", "tips", "news",
134 }
135
136 # Single-word programming languages, frameworks, runtimes, OSes, and dev tools.
137 # A bare capitalized "Python"/"React"/"Docker" query is overwhelmingly about the
138 # technology, not a company's customer reviews -- letting it through would both
139 # trigger the Chrome harvest and risk surfacing an unrelated company that shares
140 # the name. A user who genuinely wants the company can use its domain
141 # (e.g. "docker.com"), which still passes via the domain branch.
142 _TECH_TOKENS = {
143 "python", "javascript", "typescript", "java", "rust", "ruby", "php",
144 "kotlin", "scala", "golang", "swift", "elixir", "erlang", "haskell",
145 "react", "vue", "angular", "svelte", "django", "flask", "rails", "spring",
146 "node", "nodejs", "deno", "bun", "express", "nextjs", "nuxt",
147 "linux", "ubuntu", "debian", "fedora", "windows", "macos", "android",
148 "docker", "kubernetes", "k8s", "terraform", "ansible", "nginx",
149 "redis", "postgres", "postgresql", "mysql", "sqlite", "mongodb", "kafka",
150 "graphql", "webpack", "vite", "rust", "wasm",
151 }
152
153
154 def _log(msg: str) -> None:
155 log.source_log("Trustpilot", msg, tty_only=False)
156
157
158 def _is_available() -> bool:
159 """True when the trustpilot-pp-cli binary is on PATH."""
160 return shutil.which(CLI_BIN) is not None
161
162
163 def _truthy(value: Any) -> bool:
164 return str(value or "").strip().lower() in ("1", "true", "yes", "on")
165
166
167 def _harvest_allowed(config: Optional[Dict[str, Any]]) -> bool:
168 """False when the browser opt-out is set (automated/headless contexts).
169
170 Reads the opt-out from the merged config AND directly from the process
171 environment. The env fallback is load-bearing: ``config`` is assembled from
172 an allowlist in ``env.get_config``, so a fallback here guarantees the
173 documented kill-switch works even when the key is not propagated into
174 config (e.g. a bare ``LAST30DAYS_TRUSTPILOT_NO_BROWSER=1`` in cron/CI).
175 """
176 if config and _truthy(config.get(NO_BROWSER_ENV)):
177 return False
178 if _truthy(os.environ.get(NO_BROWSER_ENV)):
179 return False
180 return True
181
182
183 def _child_env() -> Dict[str, str]:
184 """Allowlisted child environment for trustpilot-pp-cli."""
185 return {
186 name: value
187 for name, value in os.environ.items()
188 if name.upper() in _CHILD_ENV_ALLOWLIST or name.upper().startswith("LC_")
189 }
190
191
192 def _is_safe_cli_arg(value: Any) -> bool:
193 """True when ``value`` is a non-empty positional CLI arg that cannot be parsed as an option."""
194 if not isinstance(value, str):
195 return False
196 text = value.strip()
197 if not text or text.startswith("-"):
198 return False
199 return not any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text)
200
201
202 def _is_valid_domain(value: Any) -> bool:
203 """True when ``value`` is a strict DNS hostname without whitespace, control chars, or leading '-'."""
204 if not isinstance(value, str):
205 return False
206 text = value.strip()
207 if not text or text.startswith("-"):
208 return False
209 return bool(_STRICT_DOMAIN_RE.fullmatch(text))
210
211
212 def is_brand_shaped(topic: str) -> bool:
213 """True when the topic looks like a company/brand Trustpilot can resolve.
214
215 A domain-like token always qualifies. Otherwise the topic must be a short
216 (<=2-word) capitalized proper noun with no generic tokens -- this lets
217 "ChowNow", "Nothing Phone", and "OpenAI" through while keeping "AI coding
218 agents", "agent memory", and "Golden State Warriors" out.
219 """
220 if not _is_safe_cli_arg(topic):
221 return False
222 text = topic.strip()
223 if _DOMAIN_RE.search(text.lower()):
224 return True
225 words = text.split()
226 if len(words) > 2:
227 return False
228 if any(w.lower() in _GENERIC_TOKENS or w.lower() in _TECH_TOKENS for w in words):
229 return False
230 # At least one token must look like a proper noun (leading capital).
231 return any(w[:1].isupper() for w in words)
232
233
234 def _company_identifier(topic: str) -> str:
235 """Pick the identifier to hand the CLI: a domain token if present, else the
236 cleaned topic string."""
237 m = _DOMAIN_RE.search(topic.lower())
238 if m:
239 return m.group(0)
240 return topic.strip()
241
242
243 def _build_info_args(identifier: str) -> List[str]:
244 cleaned = (identifier or "").strip() if isinstance(identifier, str) else ""
245 if not _is_safe_cli_arg(cleaned):
246 raise ValueError(f"invalid Trustpilot identifier: {identifier!r}")
247 return [CLI_BIN, "info", "--agent", "--", cleaned]
248
249
250 def _normalize_name(text: str) -> str:
251 """Case/whitespace/punctuation-insensitive brand-name key."""
252 # NFC unifies canonical spellings without folding full-width forms or
253 # ligatures. Keep marks and non-ASCII symbols that can distinguish brands.
254 name = unicodedata.normalize("NFC", text or "")
255 return "".join(
256 ch for ch in name.lower()
257 if ch.isalnum() or (
258 not ch.isascii() and not ch.isspace() and not unicodedata.category(ch).startswith("P")
259 )
260 )
261
262
263 # name->domain results, keyed by normalized topic. Per-topic (NOT a single
264 # process-wide slot): vs-mode resolves several entities in one process, and a
265 # single slot would serve entity A's domain to entity B.
266 _domain_cache: Dict[str, Optional[str]] = {}
267 _domain_cache_lock = threading.Lock()
268
269 _warmup_lock = threading.Lock()
270
271
272 def _reset_state_for_tests() -> None:
273 """Clear module-level caches/flags (tests only)."""
274 with _domain_cache_lock:
275 _domain_cache.clear()
276
277
278 def _select_search_hit(topic: str, hits: List[Any]) -> Optional[str]:
279 """Pick the canonical domain from search hits, or None when ambiguous.
280
281 Name-match is mandatory: review volume must never override a name
282 mismatch, or the engine attributes another company's reviews to the topic.
283 Among name-matching hits the winner must dominate on review volume
284 (DOMAIN_DOMINANCE_FACTOR); comparable volume is genuine ambiguity and
285 falls back to legacy behavior.
286 """
287 want = _normalize_name(topic)
288 if not want:
289 return None
290 matching: List[tuple[int, str]] = []
291 for hit in hits:
292 if not isinstance(hit, dict):
293 continue
294 domain = str(hit.get("domain") or hit.get("identifyingName") or "").strip()
295 name = str(hit.get("displayName") or hit.get("name") or "").strip()
296 if not _is_valid_domain(domain) or _normalize_name(name) != want:
297 continue
298 try:
299 count = int(hit.get("numberOfReviews") or 0)
300 except (TypeError, ValueError):
301 count = 0
302 matching.append((count, domain))
303 if not matching:
304 top = next(
305 (str(h.get("domain") or "").strip() for h in hits
306 if isinstance(h, dict) and _is_valid_domain(str(h.get("domain") or "").strip())),
307 "",
308 )
309 if top:
310 _log(
311 f"no name-matching search hit; top candidate was '{top}' - "
312 f"pass --trustpilot-domain to target it"
313 )
314 return None
315 matching.sort(reverse=True)
316 if len(matching) == 1:
317 return matching[0][1]
318 top_count, top_domain = matching[0]
319 runner_count, runner_domain = matching[1]
320 if top_count >= max(1, runner_count) * DOMAIN_DOMINANCE_FACTOR:
321 return top_domain
322 _log(
323 f"ambiguous search hits ('{top_domain}' vs '{runner_domain}'); "
324 f"falling back - pass --trustpilot-domain to disambiguate"
325 )
326 return None
327
328
329 def _search_domain(
330 topic: str, session_ready: Optional[Callable[[], bool]] = None,
331 ) -> Optional[str]:
332 """Resolve a company name to its Trustpilot domain via the CLI's search.
333
334 ``session_ready`` is asked right before the CLI runs (a cached answer
335 needs no session); when it says no, nothing runs and None is returned.
336
337 Cached per normalized topic (thread-safe), so repeat lookups cost one
338 subprocess while vs-mode entities still resolve independently. Only
339 definitive results are cached: a transient CLI failure (timeout, spawn
340 error, malformed JSON) returns None WITHOUT caching, so one flaky search
341 does not suppress resolution for this topic for the rest of the process.
342 """
343 cleaned = (topic or "").strip() if isinstance(topic, str) else ""
344 if not _is_safe_cli_arg(cleaned):
345 _log(f"rejecting unsafe search topic: {topic!r}")
346 return None
347 key = _normalize_name(cleaned)
348 if not key:
349 return None
350 with _domain_cache_lock:
351 if key in _domain_cache:
352 return _domain_cache[key]
353 if session_ready is not None and not session_ready():
354 return None
355 data = _run_cli(
356 [CLI_BIN, "search", "--limit", "5", "--agent", "--", cleaned],
357 timeout=SEARCH_TIMEOUT,
358 )
359 if not isinstance(data, dict) or "error" in data:
360 return None # transient failure: retry on the next lookup
361 hits = data.get("hits")
362 if not isinstance(hits, list):
363 # Degenerate payload (e.g. empty stdout parses to {}): not a
364 # definitive no-match -- do not cache, retry on the next lookup.
365 return None
366 domain = _select_search_hit(topic, hits)
367 if domain:
368 _log(f"resolved '{topic}' -> '{domain}' via search")
369 with _domain_cache_lock:
370 _domain_cache[key] = domain
371 return domain
372
373
374 def _is_session_fresh(status: Dict[str, Any]) -> bool:
375 """Read the freshness signal from an ``auth status --agent`` payload."""
376 if not isinstance(status, dict) or "error" in status:
377 return False
378 containers: List[Dict[str, Any]] = [status]
379 session = status.get("session")
380 if isinstance(session, dict):
381 containers.append(session)
382 for container in containers:
383 for key in ("isFresh", "fresh"):
384 if key in container:
385 return bool(container[key])
386 return False
387
388
389 def _session_about_to_lapse(status: Dict[str, Any]) -> bool:
390 """True when the payload dates the harvest within the margin of the CLI's
391 replay limit. A payload with no readable harvest time is not judged."""
392 containers = [status, status.get("session")] if isinstance(status, dict) else []
393 for container in containers:
394 if not isinstance(container, dict) or not container.get("harvestedAt"):
395 continue
396 try:
397 harvested = datetime.fromisoformat(str(container["harvestedAt"]).replace("Z", "+00:00"))
398 except ValueError:
399 continue
400 if harvested.tzinfo is None:
401 harvested = harvested.replace(tzinfo=timezone.utc)
402 age = (datetime.now(timezone.utc) - harvested).total_seconds()
403 return age > CLI_SESSION_SECONDS - SESSION_MARGIN_SECONDS
404 return False
405
406
407 def ensure_session_ready(
408 topic: str,
409 config: Optional[Dict[str, Any]] = None,
410 has_domain: bool = False,
411 ) -> bool:
412 """Whether the CLI's saved WAF session can be replayed right now.
413
414 Checks only: ``auth status`` is a local read. It never runs ``auth
415 login``, which launches Chrome, and a False answer means the caller must
416 not run a fetch command either, since each of those harvests by itself
417 when the session is missing or stale. There is no memo: the session lasts
418 four minutes, so every fetch asks again. Logs only structured status
419 strings; the raw CLI payload carries live WAF-token prefixes and must
420 never be logged. Never raises.
421 """
422 if not _is_available():
423 return False
424 if not _harvest_allowed(config):
425 return False
426 if not has_domain and not is_brand_shaped(topic):
427 return False
428 with _warmup_lock:
429 status = _run_cli(
430 [CLI_BIN, "auth", "status", "--agent"], timeout=AUTH_STATUS_TIMEOUT
431 )
432 if _is_session_fresh(status) and not _session_about_to_lapse(status):
433 _log("session: fresh")
434 return True
435 _log("session: missing or stale; not launching Chrome")
436 return False
437
438
439 def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
440 """Invoke trustpilot-pp-cli and parse the JSON object. Never raises."""
441 if not _is_available():
442 return {"error": f"{CLI_BIN} not on PATH"}
443 try:
444 result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env())
445 except subproc.SubprocTimeout as exc:
446 msg = _scrub_url_userinfo(str(exc))
447 _log(f"Timeout: {msg}")
448 return {"error": msg}
449 except FileNotFoundError as exc:
450 msg = _scrub_url_userinfo(str(exc))
451 _log(f"Binary missing: {msg}")
452 return {"error": msg}
453 except OSError as exc:
454 msg = _scrub_url_userinfo(str(exc))
455 _log(f"Spawn failed: {msg}")
456 return {"error": msg}
457
458 if result.returncode != 0:
459 stderr = _scrub_url_userinfo(result.stderr or "")
460 snippet = stderr.strip().splitlines()[:1]
461 first = snippet[0] if snippet else f"exit {result.returncode}"
462 # A --local miss is the normal "nothing cached" answer, and the CLI's
463 # message for it suggests a command that opens a browser.
464 if "--local" not in cmd:
465 _log(f"CLI exit {result.returncode}: {first}")
466 return {"error": first}
467
468 stdout = result.stdout or ""
469 if not stdout.strip():
470 return {}
471 try:
472 data = json.loads(stdout)
473 except json.JSONDecodeError as exc:
474 msg = _scrub_url_userinfo(str(exc))
475 _log(f"JSON decode failed: {msg}")
476 return {"error": f"json decode: {msg}"}
477 return data if isinstance(data, dict) else {}
478
479
480 def search_trustpilot(
481 topic: str,
482 from_date: str,
483 to_date: str,
484 depth: str = "default",
485 config: Optional[Dict[str, Any]] = None,
486 explicit_domain: Optional[str] = None,
487 domain_is_hint: bool = False,
488 ) -> Dict[str, Any]:
489 """Look up a company's Trustpilot sentiment, gated on a brand-shaped topic.
490
491 ``explicit_domain`` is used verbatim as the CLI identifier and bypasses
492 the brand-shape gate (an explicit domain is proof of brand intent). A
493 user-set domain is verbatim-final; a resolved hint
494 (``domain_is_hint=True``) retries via the CLI search when the lookup
495 misses, since auto-resolve can guess a plausible-but-wrong domain (the
496 official site is not always Trustpilot's canonical identifyingName).
497
498 Without an explicit domain, a bare company name resolves via the CLI's
499 ``search`` (cached per topic) before falling back to the cleaned topic.
500
501 Returns ``{"results": [info_dict]}`` for a resolved company, or
502 ``{"results": []}`` when the topic is not brand-shaped, the browser
503 opt-out is set, or the CLI fails. With no replayable session nothing is
504 fetched and the result carries ``needs_session`` and ``SESSION_NEEDED``
505 under ``skipped``: an expected skip, not an error.
506 """
507 raw_explicit = (explicit_domain or "").strip() if isinstance(explicit_domain, str) else ""
508 if raw_explicit and not _is_valid_domain(raw_explicit):
509 _log(_INVALID_DOMAIN_ERROR)
510 return {"results": [], "error": _INVALID_DOMAIN_ERROR}
511 explicit_domain = raw_explicit or None
512 user_domain = bool(explicit_domain) and not domain_is_hint
513 # Only a USER-set domain proves brand intent and bypasses the brand-shape
514 # gate. An auto-resolved hint must not widen activation beyond
515 # brand-shaped topics, or a generic topic that happens to yield a hint
516 # would trigger a Chrome harvest -- violating the module's documented
517 # "never harvests on non-company topics" contract.
518 if not user_domain and not is_brand_shaped(topic):
519 return {"results": []}
520 if not _is_available():
521 return {"results": [], "error": f"{CLI_BIN} not on PATH"}
522 if not _harvest_allowed(config):
523 _log("skipped: browser opt-out set")
524 return {"results": []}
525 # Asked before every fetch command (all gates above have passed, so this
526 # never fires for topics the source would not fetch).
527 def session_ready() -> bool:
528 return ensure_session_ready(topic, config=config, has_domain=bool(explicit_domain))
529
530 def without_session(identifier: Optional[str]) -> Dict[str, Any]:
531 """The cached record for a known domain, else the quiet skip."""
532 cached = _cached_info(identifier) if identifier else None
533 if cached:
534 return {"results": [cached]}
535 _log(f"skipped: {SESSION_NEEDED}")
536 # No "error" key: a skipped lane is not a failed source.
537 return {"results": [], "needs_session": True, "skipped": SESSION_NEEDED}
538
539 # Cached records are keyed by domain; a bare name cannot be looked up
540 # without the session its name -> domain search needs.
541 known_domain = explicit_domain or (
542 _company_identifier(topic) if _DOMAIN_RE.search(topic.lower()) else None
543 )
544 if not session_ready():
545 return without_session(known_domain)
546 # Retry-budget timer starts AFTER the session check, so it measures the
547 # info call itself.
548 started = time.monotonic()
549 if explicit_domain:
550 identifier = explicit_domain
551 else:
552 identifier = _company_identifier(topic)
553 if not _DOMAIN_RE.search(topic.lower()):
554 # No domain token in the topic: Trustpilot pages are keyed by
555 # domain, so resolve name -> domain before the info lookup.
556 resolved_domain = _search_domain(topic, session_ready)
557 identifier = resolved_domain or identifier
558 if not session_ready():
559 return without_session(resolved_domain)
560 if not _is_safe_cli_arg(identifier):
561 _log(f"rejecting unsafe identifier: {identifier!r}")
562 return {"results": []}
563 _log(f"info '{identifier}'")
564 data = _run_cli(_build_info_args(identifier), timeout=SEARCH_TIMEOUT)
565 if ("error" in data or not data) and explicit_domain and domain_is_hint:
566 # The auto-resolved hint missed. Only user-set flags are
567 # verbatim-final; a hint falls through to the search resolution.
568 # Skip the retry chain when the first lookup already consumed a full
569 # single-call budget (hung CLI) -- one stream must not chain three
570 # sequential SEARCH_TIMEOUT-bound subprocesses.
571 if time.monotonic() - started < SEARCH_TIMEOUT:
572 resolved = _search_domain(topic, session_ready)
573 if resolved and _is_valid_domain(resolved) and resolved != identifier and session_ready():
574 _log(f"hint '{identifier}' missed; retrying via search as '{resolved}'")
575 data = _run_cli(_build_info_args(resolved), timeout=SEARCH_TIMEOUT)
576 if "error" in data or not data:
577 return {"results": []}
578 return {"results": [data]}
579
580
581 def _cache_age(info: Dict[str, Any]) -> Optional[tuple[str, Optional[str]]]:
582 """``("cached 3 days ago", "YYYY-MM-DD")`` for a cached record: its age
583 label and the UTC date it was fetched. None when it is too old to use. A
584 record with no readable fetch time is used, says so, and has no date."""
585 raw = info.get("fetchedAt") or info.get("updatedAt") or info.get("updated_at")
586 try:
587 fetched = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
588 except ValueError:
589 return "cached, age unknown", None
590 if fetched.tzinfo is None:
591 fetched = fetched.replace(tzinfo=timezone.utc)
592 fetched = fetched.astimezone(timezone.utc)
593 days = max(0, (datetime.now(timezone.utc) - fetched).days)
594 if days > CACHE_MAX_AGE_DAYS:
595 return None
596 fetched_date = fetched.date().isoformat()
597 if days == 0:
598 return "cached today", fetched_date
599 return f"cached {days} day{'s' if days != 1 else ''} ago", fetched_date
600
601
602 def _cached_info(identifier: str) -> Optional[Dict[str, Any]]:
603 """The CLI's cached company record for a domain, labelled with its age.
604
605 ``info --local --agent -- <domain>`` reads the local store and needs no
606 session, so it never opens a browser. None when nothing usable is cached.
607 """
608 cleaned = (identifier or "").strip() if isinstance(identifier, str) else ""
609 if not _is_valid_domain(cleaned):
610 _log(f"rejecting invalid cached-info domain: {identifier!r}")
611 return None
612 data = _run_cli(
613 [CLI_BIN, "info", "--local", "--agent", "--", cleaned], timeout=LOCAL_READ_TIMEOUT
614 )
615 if not isinstance(data, dict) or not data or "error" in data:
616 return None
617 age = _cache_age(data)
618 if age is None:
619 _log(f"cached record for '{identifier}' is over {CACHE_MAX_AGE_DAYS} days old; not used")
620 return None
621 label, fetched_date = age
622 _log(f"no fresh session; using the cached record for '{identifier}' ({label})")
623 return {**data, "_cache_label": label, "_cache_date": fetched_date}
624
625
626 def can_run_now(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
627 """Whether a run started now could get Trustpilot data without a browser.
628
629 True with a replayable session, or with at least one cached company
630 record (``doctor-tp`` counts them; whether it covers a given company is
631 known only once its domain is). Local reads only; never raises.
632 """
633 answer = {"can_run": False, "session_fresh": False, "cached_companies": 0}
634 if not _is_available() or not _harvest_allowed(config):
635 return answer
636 status = _run_cli([CLI_BIN, "auth", "status", "--agent"], timeout=LOCAL_READ_TIMEOUT)
637 answer["session_fresh"] = _is_session_fresh(status) and not _session_about_to_lapse(status)
638 if not answer["session_fresh"]:
639 cache = _run_cli([CLI_BIN, "doctor-tp", "--agent"], timeout=LOCAL_READ_TIMEOUT)
640 answer["cached_companies"] = _coerce_int(
641 cache.get("companies") if isinstance(cache, dict) else None
642 ) or 0
643 answer["can_run"] = bool(answer["session_fresh"] or answer["cached_companies"])
644 return answer
645
646
647 def _coerce_float(value: Any) -> Optional[float]:
648 try:
649 return float(value)
650 except (TypeError, ValueError):
651 return None
652
653
654 def _coerce_int(value: Any) -> Optional[int]:
655 try:
656 return int(value)
657 except (TypeError, ValueError):
658 return None
659
660
661 def parse_trustpilot_response(
662 response: Dict[str, Any],
663 query: str = "",
664 ) -> List[Dict[str, Any]]:
665 """Parse a Trustpilot ``info`` envelope into a single normalized item.
666
667 The AI summary is the body (it already balances positive and negative
668 sentiment). TrustScore and review count feed engagement and metadata.
669 Returns dicts ready for ``normalize._normalize_trustpilot``.
670 """
671 raw = response.get("results") if isinstance(response, dict) else None
672 if not isinstance(raw, list) or not raw:
673 return []
674 info = raw[0]
675 if not isinstance(info, dict):
676 return []
677
678 resolved_name = str(info.get("name") or info.get("displayName") or "").strip()
679 ai_summary = str(info.get("aiSummary") or info.get("summary") or "").strip()
680 trust_score = _coerce_float(info.get("trustScore") or info.get("score"))
681 review_count = _coerce_int(
682 info.get("reviewCount") or info.get("numberOfReviews") or info.get("total")
683 )
684 url = str(info.get("url") or "").strip()
685 domain = str(info.get("domain") or info.get("identifyingName") or "").strip()
686 if not url and domain:
687 url = f"https://www.trustpilot.com/review/{domain}"
688
689 # Require substantive content from the company record itself; do not
690 # fabricate an item from the query alone when the CLI returned nothing.
691 if not resolved_name and not ai_summary and trust_score is None and review_count is None:
692 return []
693
694 name = resolved_name or query.strip()
695
696 title = f"{name} on Trustpilot" if name else "Trustpilot reviews"
697 if trust_score is not None:
698 title = f"{name}: TrustScore {trust_score}" if name else title
699
700 engagement: Dict[str, float | int] = {}
701 if review_count is not None:
702 engagement["reviews"] = review_count
703 if trust_score is not None:
704 engagement["trustScore"] = trust_score
705
706 relevance = token_overlap_relevance(query, name) if (query and name) else 0.7
707
708 why = "Trustpilot brand sentiment"
709 if trust_score is not None and review_count is not None:
710 why = f"Trustpilot: TrustScore {trust_score} across {review_count} reviews"
711 elif trust_score is not None:
712 why = f"Trustpilot: TrustScore {trust_score}"
713 # A cached record (no fresh session this run) says so wherever it is read.
714 cache_label = str(info.get("_cache_label") or "").strip()
715 if cache_label:
716 title = f"{title} ({cache_label})"
717 why = f"{why} ({cache_label})"
718
719 return [
720 {
721 "id": domain or name or "trustpilot",
722 "title": title,
723 "url": url,
724 "summary": ai_summary,
725 "name": name,
726 "trustScore": trust_score,
727 "reviewCount": review_count,
728 # A live TrustScore is a fact about now. A cached record is dated
729 # by its fetch, and undated when the fetch time is unreadable.
730 "date": info.get("_cache_date") if cache_label else dates.get_date_range(1)[1],
731 "engagement": engagement,
732 "relevance": round(min(1.0, max(0.4, relevance)), 2),
733 "why_relevant": why,
734 }
735 ]
736
736 lines PYTHON