Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(trustpilot): resolve name->domain, session warm-up, single-fetch cap (#745)

Matt Van Horn443b05f3303b
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 0c2dbe25..4900bc09 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -97,7 +97,7 @@ The project-scoped file is useful for **intentional per-client setups**: drop a
| Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) |
| arXiv | `arxiv-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install arxiv --cli-only`) | always on if `arxiv-pp-cli` on PATH; fires on research/technical topics and stays quiet otherwise (relevance + 365-day recency gating) | yes (free, keyless) |
| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; syncs a local headline cache once per run, then searches | yes (free, keyless) |
-| Trustpilot | `trustpilot-pp-cli` on PATH (NOT auto-installed; install on demand via `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`) + `INCLUDE_SOURCES` contains `trustpilot` | **opt-in, off by default**; when enabled, activates only on company/brand topics. Does a one-time ~10s headless-Chrome WAF-cookie harvest on first company lookup (set `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` to disable in cron/CI) | yes (no API key; cookie-replay after the one-time harvest) |
+| Trustpilot | `trustpilot-pp-cli` on PATH (NOT auto-installed; install on demand via `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`) + `INCLUDE_SOURCES` contains `trustpilot` | **opt-in, off by default**; when enabled, activates only on company/brand topics — or on any topic when `--trustpilot-domain=<domain>` pins the review page explicitly (bypasses the brand-shape gate; also the per-entity `trustpilot_domain` key in `--competitors-plan`). Bare company names auto-resolve to the review-page domain via the CLI's search. The session warms once before the search fan-out; a stale session does a ~10s headless-Chrome WAF-cookie harvest (set `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` to disable in cron/CI) | yes (no API key; cookie-replay after the one-time harvest) |
| X / Twitter | one of: `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, `SCRAPECREATORS_API_KEY`, or `FROM_BROWSER` (cookie-jar auth) | X items in results | cookie-jar / Bird = free; Xquik / xAI / ScrapeCreators = key-based |
| TikTok | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok` | TikTok items | 10K free calls |
| Instagram | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `instagram` | Instagram Reels | 10K free calls; raise `LAST30DAYS_TRANSCRIPT_TIMEOUT` (default 30s) if SC is slow on your network |
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 8728ea19..493f2d76 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -715,6 +715,7 @@ Before running the engine, determine which flags apply to this topic and resolve
| `--x-related={h1,h2,...}` | Step 0.5 (Section A below) | Topic has associated entities (founders, commentators, spouse, collaborators, media handles) |
| `--github-user={user}` | Step 0.5b | Topic is a person who ships code (developer, engineer, CEO-who-codes, researcher) |
| `--github-repo={owner/repo}` | Step 0.5c | Topic is a product / project / open-source tool |
+| `--trustpilot-domain={domain}` | Step 0.5d | Topic is a company / brand / service with a Trustpilot presence AND the run includes the Trustpilot source |
| `--subreddits={sub1,sub2,...}` | Step 0.55 | Always — almost every topic has active Reddit communities |
| `--tiktok-hashtags={h1,h2,...}` | Step 0.55 | Always — inferred from topic |
| `--tiktok-creators={c1,c2,...}` | Step 0.55 | Creator / influencer / brand topics |
@@ -849,6 +850,28 @@ Project-mode GitHub fetches live star counts, README snippets, latest releases,
Store: `RESOLVED_GITHUB_REPOS = {comma-separated owner/repo or empty}`
+### Step 0.5d: Resolve Trustpilot Domain (if topic is a company/brand and Trustpilot is active)
+
+If the run includes the Trustpilot source (`INCLUDE_SOURCES=trustpilot` or an explicit `--search` list) and TOPIC is a company, brand, or service, resolve its Trustpilot review-page domain. Trustpilot pages are keyed by domain (`www.thriftbooks.com`), not company name — a bare name 404s.
+
+**You usually already have it.** Step 0.55 item 6 (first-party positioning) fetches the official site — capture the bare hostname while you're there. When positioning wasn't fetched, one lookup covers it:
+
+```
+WebSearch("{TOPIC} official site")
+```
+
+Pass to the CLI: `--trustpilot-domain={domain}` (e.g., `--trustpilot-domain=www.thriftbooks.com`)
+
+The flag is used verbatim and bypasses the engine's brand-shape gate, so it also unlocks Trustpilot for multi-word company names ("Stanley Steemer carpet cleaning"). For comparisons, put a per-entity `trustpilot_domain` in each PEER entity's `--competitors-plan` entry; the MAIN topic's domain must ride the outer `--trustpilot-domain` flag (the engine does not read a main-topic entry out of the plan).
+
+**A miss is not fatal.** When the flag is absent, the engine resolves name → domain itself via the CLI's search (and headless `--auto-resolve` runs fill a hint the engine verifies). Resolve the flag when the domain is already in hand or the company name is ambiguous (lookalike or same-named companies) — an explicit domain is the only way to guarantee the right company.
+
+**Skip this step if:**
+- The Trustpilot source is not active for this run
+- TOPIC is a person, event, or abstract concept (no company reviews to fetch)
+
+Store: `RESOLVED_TRUSTPILOT_DOMAIN = {domain or empty}`
+
---
## Agent Mode (--agent flag)
@@ -942,7 +965,7 @@ PLAN_EOF
**Keep the heredoc marker quoted as `'PLAN_EOF'`.** Quoting suppresses shell interpolation so apostrophes, `$`, backticks, etc. pass through verbatim. If you ever switch to an unquoted `<<PLAN_EOF`, every variable reference and apostrophe inside the JSON becomes a parse hazard.
-Topic A (the main topic, first in the vs-string) uses outer `--x-handle`, `--x-related`, `--subreddits`, `--github-user`, `--github-repo`, `--tiktok-*`, `--ig-creators` as usual. Topics B and C get their targeting from `--competitors-plan` entries (keyed by entity name, case-insensitive).
+Topic A (the main topic, first in the vs-string) uses outer `--x-handle`, `--x-related`, `--subreddits`, `--github-user`, `--github-repo`, `--trustpilot-domain`, `--tiktok-*`, `--ig-creators` as usual. Topics B and C get their targeting from `--competitors-plan` entries (keyed by entity name, case-insensitive) — the engine does NOT read a main-topic entry out of the plan, so the main topic's Trustpilot domain must ride the outer flag.
**Step 0.55 for N entities.** The same pre-research protocol that applies to a single-entity topic applies to EACH entity in a vs-run. For N=3, that means 3 WebSearches for X handles, 3 for subreddits, 3 for GitHub, 3 for news context — or equivalent batched queries. A `## Resolved Entities` block with dashes for any entity means you skipped Step 0.55 for that one. Re-run with a corrected plan.
@@ -968,7 +991,7 @@ Topic A (the main topic, first in the vs-string) uses outer `--x-handle`, `--x-r
- `--competitors` (bare) - signals the hosting model to discover 2 peers (3-way total).
- `--competitors=N` - N peers (1..6; out-of-range clamps with stderr warning).
- `--competitors-list="A,B,C"` - minimum escape hatch; names only, no per-entity targeting. Peer sub-runs fall back to planner defaults (visibly thinner data).
-- `--competitors-plan '{entity: {x_handle, subreddits, github_user, github_repos, context}}'` - full per-entity targeting; implies vs-mode; preferred.
+- `--competitors-plan '{entity: {x_handle, subreddits, github_user, github_repos, trustpilot_domain, context}}'` - full per-entity targeting; implies vs-mode; preferred.
- `--polymarket-keywords "kw1,kw2"` - disambiguate Polymarket for ambiguous single-token topics ("Warriors" → `nba,gsw,golden-state`).
- `--hiring-signals` - deep-dive into public jobs/careers evidence for company focus signals. Use signal language only: leaning into, investing in, increasing focus, priority shift. Do NOT claim exact roadmap predictions from job postings.
@@ -1097,6 +1120,7 @@ Per-entity lookup types to resolve:
2. **Project GitHub repo** - `owner/repo` format (e.g., `openai/openai-python`)
3. **Founder/maintainer X handle** - the person or team behind the project
4. **Relevant subreddits** - project-specific subreddits (e.g., `r/openclaw`) AND general-category subreddits (e.g., `r/LocalLLaMA`)
+5. **Trustpilot domain** (only when the Trustpilot source is active and the entity is a company/brand/service) - the entity's Trustpilot review-page domain per Step 0.5d; peers carry it as `trustpilot_domain` in their `--competitors-plan` entry, the main topic via the outer `--trustpilot-domain` flag
Example batching for "OpenClaw vs Hermes vs Paperclip":
@@ -1131,10 +1155,11 @@ Resolved:
- Reddit: r/{sub1}, r/{sub2}, r/{sub3}, r/{peer1}, r/{peer2} (+ {category_id} peers)
- TikTok: #{hashtag1}, #{hashtag2}
- YouTube: {query1}, {query2}
+- Trustpilot: {domain}
- Positioning: "{one-line stated value prop}" (first-party)
```
-Only show lines for platforms where something was resolved. Skip empty lines. On the Reddit line, the trailing `(+ {category_id} peers)` annotation appears when Step 0.55 Section 2a added category-peer subs. Omit the annotation when the topic had no matching category. The `Positioning:` line appears for company / product / service topics (from Step 0.55 item 6); omit it for people, events, abstract concepts, and ownerless topics. This display replaces the old "Parsed intent" block with something more useful.
+Only show lines for platforms where something was resolved. Skip empty lines. On the Reddit line, the trailing `(+ {category_id} peers)` annotation appears when Step 0.55 Section 2a added category-peer subs. Omit the annotation when the topic had no matching category. The `Positioning:` line appears for company / product / service topics (from Step 0.55 item 6); omit it for people, events, abstract concepts, and ownerless topics. The `Trustpilot:` line appears only when Step 0.5d resolved a domain (company/brand topic with the Trustpilot source active). This display replaces the old "Parsed intent" block with something more useful.
---
@@ -1292,6 +1317,7 @@ Then add to the engine command:
- `--ig-creators={RESOLVED_IG_CREATORS}` (from Step 0.55)
- `--github-user={RESOLVED_GITHUB_USER}` (from Step 0.5b, person topics only)
- `--github-repo={RESOLVED_GITHUB_REPOS}` (from Step 0.5c, product/project topics only)
+- `--trustpilot-domain={RESOLVED_TRUSTPILOT_DOMAIN}` (from Step 0.5d, company/brand topics when the Trustpilot source is active)
- Omit any flag where the value was not resolved (empty).
**If you skipped Steps 0.55 and 0.75 (no WebSearch -- OpenClaw, Codex, etc.), add:**
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 6f7b4e85..ae86eb85 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -382,6 +382,7 @@ def build_parser() -> argparse.ArgumentParser:
help="Use web search to discover subreddits/handles before planning (for platforms without WebSearch)")
parser.add_argument("--github-user", help="GitHub username for person-mode search (e.g., steipete)")
parser.add_argument("--github-repo", help="Comma-separated owner/repo for project-mode search (e.g., openclaw/openclaw,paperclipai/paperclip)")
+ parser.add_argument("--trustpilot-domain", help="Trustpilot review-page domain for the topic (e.g., www.thriftbooks.com). Used verbatim and bypasses the brand-shape gate; find it with `trustpilot-pp-cli search '<name>'`.")
parser.add_argument(
"--competitors",
nargs="?",
@@ -451,7 +452,7 @@ def parse_competitors_plan(raw: str | None) -> dict[str, dict]:
raise SystemExit(2)
known_fields = {
"x_handle", "x_related", "subreddits",
- "github_user", "github_repos", "context",
+ "github_user", "github_repos", "trustpilot_domain", "context",
}
normalized: dict[str, dict] = {}
for entity, entry in parsed.items():
@@ -516,6 +517,15 @@ def subrun_kwargs_for(
if isinstance(github_repos, list):
github_repos = [r.strip() for r in github_repos if r.strip() and "/" in r.strip()] or None
+ trustpilot_domain = _choose("trustpilot_domain", "trustpilot_domain")
+ if isinstance(trustpilot_domain, str):
+ trustpilot_domain = trustpilot_domain.strip() or None
+ # Provenance: a plan-supplied domain is user-set (verbatim-final); one that
+ # only came from auto_resolve is a hint that retries via search on a miss.
+ trustpilot_domain_is_hint = bool(
+ trustpilot_domain and not plan_entry.get("trustpilot_domain")
+ )
+
context = plan_entry.get("context") or resolved.get("context") or ""
return {
@@ -524,6 +534,8 @@ def subrun_kwargs_for(
"subreddits": subreddits,
"github_user": github_user,
"github_repos": github_repos,
+ "trustpilot_domain": trustpilot_domain,
+ "_trustpilot_domain_is_hint": trustpilot_domain_is_hint,
"_context": context,
}
@@ -1123,6 +1135,7 @@ def main() -> int:
# This is the engine-side equivalent of SKILL.md Steps 0.55/0.75 for platforms
# without WebSearch (OpenClaw, Codex, raw CLI).
repos_from_auto_resolve = False
+ trustpilot_domain_is_hint = False
if args.auto_resolve and not external_plan:
from lib import resolve
resolution = resolve.auto_resolve(topic, config)
@@ -1141,6 +1154,12 @@ def main() -> int:
# mark so we don't re-canonicalize below and clobber its relevance order.
repos_from_auto_resolve = True
sys.stderr.write(f"[AutoResolve] GitHub repos: {args.github_repo}\n")
+ if resolution.get("trustpilot_domain") and not args.trustpilot_domain:
+ # Hint provenance matters: only user-set flags are verbatim-final;
+ # a resolved hint retries via the CLI search when it misses.
+ args.trustpilot_domain = resolution["trustpilot_domain"]
+ trustpilot_domain_is_hint = True
+ sys.stderr.write(f"[AutoResolve] Trustpilot domain: {args.trustpilot_domain} (hint)\n")
if resolution.get("context"):
# Inject context into external_plan metadata for the planner to use
if not external_plan:
@@ -1151,6 +1170,7 @@ def main() -> int:
github_user = args.github_user.lstrip("@").lower() if args.github_user else None
github_repos = [r.strip() for r in args.github_repo.split(",") if r.strip() and "/" in r.strip()] if args.github_repo else None
+ trustpilot_domain = args.trustpilot_domain.strip() if args.trustpilot_domain else None
# Only canonicalize when repos came from a user-supplied --github-repo flag.
# When repos_from_auto_resolve is True, auto_resolve already ran
@@ -1234,6 +1254,8 @@ def main() -> int:
as_of_date=args.as_of_date,
github_user=github_user,
github_repos=github_repos,
+ trustpilot_domain=trustpilot_domain,
+ trustpilot_domain_is_hint=trustpilot_domain_is_hint,
internal_subrun=comp_enabled,
hiring_signals_mode=args.hiring_signals,
)
@@ -1243,6 +1265,7 @@ def main() -> int:
"subreddits": list(subreddits or []),
"github_user": (github_user or ""),
"github_repos": list(github_repos or []),
+ "trustpilot_domain": (trustpilot_domain or ""),
"context": config.get("_auto_resolve_context", "") or "",
}
return r
@@ -1304,6 +1327,7 @@ def main() -> int:
"subreddits": [],
"github_user": "",
"github_repos": [],
+ "trustpilot_domain": "",
"context": "",
}
# Skip engine-internal auto_resolve when the hosting model
@@ -1330,6 +1354,7 @@ def main() -> int:
resolved["subreddits"] = list(r.get("subreddits") or [])
resolved["github_user"] = r.get("github_user", "") or ""
resolved["github_repos"] = list(r.get("github_repos") or [])
+ resolved["trustpilot_domain"] = r.get("trustpilot_domain", "") or ""
resolved["context"] = r.get("context", "") or ""
kwargs = subrun_kwargs_for(entity, plan_entry, resolved=resolved)
# Record effective per-entity targeting for the Resolved block.
@@ -1339,6 +1364,7 @@ def main() -> int:
"subreddits": kwargs["subreddits"] or [],
"github_user": kwargs["github_user"] or "",
"github_repos": kwargs["github_repos"] or [],
+ "trustpilot_domain": kwargs["trustpilot_domain"] or "",
"context": kwargs["_context"],
}
if kwargs["_context"]:
@@ -1361,6 +1387,8 @@ def main() -> int:
subreddits=kwargs["subreddits"],
github_user=kwargs["github_user"],
github_repos=kwargs["github_repos"],
+ trustpilot_domain=kwargs["trustpilot_domain"],
+ trustpilot_domain_is_hint=kwargs["_trustpilot_domain_is_hint"],
web_backend=args.web_backend,
lookback_days=args.lookback_days,
as_of_date=args.as_of_date,
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index f0a213e2..da1aae78 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -72,7 +72,10 @@ SEARCH_ALIAS = {
"xquik": "x", # xquik is a backend of the single "x" source, not its own source
}
-MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1}
+# trustpilot is capped at 1: every subquery would use the identical company
+# identifier, so N streams are pure redundancy -- and each extra stream risks
+# its own WAF-cookie Chrome harvest.
+MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1, "trustpilot": 1}
# Per-handle result caps for the X handle-search lanes. The FROM lane (the
# subject's own timeline) is the single best source for a person topic, so it
@@ -341,6 +344,8 @@ def run(
as_of_date: str | None = None,
github_user: str | None = None,
github_repos: list[str] | None = None,
+ trustpilot_domain: str | None = None,
+ trustpilot_domain_is_hint: bool = False,
hiring_signals_mode: bool = False,
internal_subrun: bool = False,
) -> schema.Report:
@@ -493,6 +498,12 @@ def run(
except Exception as exc:
bundle.errors_by_source["github"] = f"Person-mode failed: {exc}"
+ # Trustpilot session warm-up happens inside search_trustpilot at the
+ # first (capped, single) fetch -- lazily, so it never delays the other
+ # sources' streams and never fires for runs whose plan fetches no
+ # Trustpilot. The module-level lock in lib/trustpilot.py serializes
+ # concurrent vs-mode sub-runs so they never race Chrome harvests.
+
# Thread-safe set prevents redundant fetches after a source returns 429
rate_limited_sources: set[str] = set()
rate_limit_lock = threading.Lock()
@@ -541,6 +552,8 @@ def run(
tiktok_hashtags=tiktok_hashtags,
tiktok_creators=tiktok_creators,
ig_creators=ig_creators,
+ trustpilot_domain=trustpilot_domain,
+ trustpilot_domain_is_hint=trustpilot_domain_is_hint,
)
] = (subquery, source)
@@ -1124,7 +1137,12 @@ def _retry_thin_sources(
for source in subquery.sources:
if source not in planned_sources:
planned_sources.append(source)
- _skip = skip_sources or set()
+ # trustpilot returns at most ONE item by design, so the "<3 items" rule
+ # would re-fetch it after every successful lookup -- bypassing
+ # MAX_SOURCE_FETCHES and re-resolving WITHOUT the caller's
+ # --trustpilot-domain (a lookalike-misattribution path). Its thin result
+ # is its normal success state; never retry it here.
+ _skip = (skip_sources or set()) | {"trustpilot"}
thin_sources = [
source
for source in planned_sources
@@ -1270,6 +1288,8 @@ def _retrieve_stream(
tiktok_hashtags: list[str] | None = None,
tiktok_creators: list[str] | None = None,
ig_creators: list[str] | None = None,
+ trustpilot_domain: str | None = None,
+ trustpilot_domain_is_hint: bool = False,
) -> tuple[list[dict], dict]:
# Early exit if source was rate-limited by a sibling future
if rate_limited_sources is not None and source in rate_limited_sources:
@@ -1522,7 +1542,9 @@ def _retrieve_stream(
# per-subquery search_query, so the company is detected consistently.
relevance_topic = raw_topic or topic or subquery.search_query
result = trustpilot.search_trustpilot(
- relevance_topic, from_date, to_date, depth=depth, config=config
+ relevance_topic, from_date, to_date, depth=depth, config=config,
+ explicit_domain=trustpilot_domain,
+ domain_is_hint=trustpilot_domain_is_hint,
)
return trustpilot.parse_trustpilot_response(result, query=relevance_topic), {}
if source == "bluesky":
diff --git a/skills/last30days/scripts/lib/resolve.py b/skills/last30days/scripts/lib/resolve.py
index a2ecfc31..c9ed3974 100644
--- a/skills/last30days/scripts/lib/resolve.py
+++ b/skills/last30days/scripts/lib/resolve.py
@@ -139,6 +139,47 @@ def _extract_github_user(items: list[dict]) -> str:
return max(counts, key=counts.get)
+# Hosts that can never be a brand's own site; their presence in results is
+# platform noise, not an official-domain signal.
+_PLATFORM_HOSTS = {
+ "reddit.com", "x.com", "twitter.com", "github.com", "youtube.com",
+ "facebook.com", "instagram.com", "tiktok.com", "linkedin.com",
+ "wikipedia.org", "medium.com", "trustpilot.com", "crunchbase.com",
+ "bloomberg.com", "apple.com", "play.google.com", "google.com",
+ "threads.com", "pinterest.com", "glassdoor.com", "indeed.com",
+ "news.ycombinator.com", "substack.com", "amazon.com", "ebay.com",
+}
+
+
+def _extract_official_domain(topic: str, items: list[dict]) -> str:
+ """Extract the brand's own domain from search-result URLs.
+
+ Conservative on purpose: only a hostname whose registrable label
+ normalizes to the topic name qualifies ("ThriftBooks" -> thriftbooks.com).
+ This feeds Trustpilot targeting as a HINT (the engine retries via the
+ CLI's own search when the hint misses), so a miss here is cheap and a
+ wrong guess is recoverable.
+ """
+ want = re.sub(r"[^a-z0-9]", "", topic.lower())
+ if not want:
+ return ""
+ host_pattern = re.compile(r"https?://([A-Za-z0-9.-]+)")
+ for item in items:
+ for source in [item.get("url", ""), f"{item.get('title', '')} {item.get('snippet', '')}"]:
+ for host in host_pattern.findall(source):
+ host = host.lower().strip(".")
+ bare = host.removeprefix("www.")
+ if any(bare == p or bare.endswith("." + p) for p in _PLATFORM_HOSTS):
+ continue
+ labels = bare.split(".")
+ if len(labels) < 2:
+ continue
+ registrable = labels[-2] if labels[-2] not in ("co", "com") or len(labels) < 3 else labels[-3]
+ if re.sub(r"[^a-z0-9]", "", registrable) == want:
+ return bare
+ return ""
+
+
def _extract_github_repos(items: list[dict]) -> list[str]:
"""Extract owner/repo strings from search results."""
repo_pattern = re.compile(r"github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)")
@@ -280,6 +321,7 @@ def auto_resolve(topic: str, config: dict) -> dict:
"x_handle": "",
"github_user": "",
"github_repos": [],
+ "trustpilot_domain": "",
"context": "",
"category": None,
"searches_run": 0,
@@ -329,16 +371,23 @@ def auto_resolve(topic: str, config: dict) -> dict:
github_user = _extract_github_user(results.get("github", []))
github_repos = canonicalize_github_repos(topic, _extract_github_repos(results.get("github", [])))
context = _build_context_summary(results.get("news", []))
+ # Official-site domain doubles as the Trustpilot targeting hint (review
+ # pages are keyed by domain). Scan news first (official sites surface in
+ # coverage), then the handle query's profile-adjacent results.
+ trustpilot_domain = _extract_official_domain(
+ topic, (results.get("news") or []) + (results.get("x_handle") or [])
+ )
subreddits, category = _merge_category_peers(topic, subreddits)
- _log(f"Resolved {len(subreddits)} subreddits, x_handle={x_handle!r}, github_user={github_user!r}, github_repos={github_repos!r}, context_len={len(context)}, category={category!r}")
+ _log(f"Resolved {len(subreddits)} subreddits, x_handle={x_handle!r}, github_user={github_user!r}, github_repos={github_repos!r}, trustpilot_domain={trustpilot_domain!r}, context_len={len(context)}, category={category!r}")
return {
"subreddits": subreddits,
"x_handle": x_handle,
"github_user": github_user,
"github_repos": github_repos,
+ "trustpilot_domain": trustpilot_domain,
"context": context,
"category": category,
"searches_run": searches_run,
diff --git a/skills/last30days/scripts/lib/trustpilot.py b/skills/last30days/scripts/lib/trustpilot.py
index b809f28d..f61ecea2 100644
--- a/skills/last30days/scripts/lib/trustpilot.py
+++ b/skills/last30days/scripts/lib/trustpilot.py
@@ -15,12 +15,24 @@ Default-on safety (three gates):
company/brand -- a domain-like token, or a short (<=2-word) capitalized
proper noun. Generic phrases ("AI coding agents", "agent memory") and
longer multi-word phrases never call the CLI, so Trustpilot stays quiet --
- and never harvests Chrome -- on non-company topics.
+ and never harvests Chrome -- on non-company topics. An explicit resolved
+ domain (``--trustpilot-domain`` or an auto-resolve hint) bypasses this
+ gate: an explicit domain is proof of brand intent.
2. Browser opt-out. Automated contexts (cron, CI, the eval harness) can set
``LAST30DAYS_TRUSTPILOT_NO_BROWSER`` to disable the source entirely, so a
headless run never spawns the cookie harvest.
3. Graceful degradation. Any CLI failure (no Chrome, expired cookie that
cannot re-harvest, timeout) degrades to empty results, never an error.
+
+Domain resolution: Trustpilot review pages are keyed by domain
+(``www.thriftbooks.com``), not company name -- ``info ThriftBooks`` 404s.
+Priority chain: user flag (verbatim) > auto-resolve hint (retries via search
+on a miss) > domain token in the topic > CLI ``search`` name->domain lookup
+(cached per topic) > cleaned topic (legacy behavior).
+
+Session pre-flight: ``ensure_session_ready`` performs one serialized
+``auth status`` / ``auth login`` before the parallel fan-out so concurrent
+streams and vs-mode sub-runs never race their own Chrome harvests.
"""
from __future__ import annotations
@@ -29,6 +41,8 @@ import json
import os
import re
import shutil
+import threading
+import time
from typing import Any, Dict, List, Optional
from . import dates, log, subproc
@@ -39,8 +53,16 @@ CLI_BIN = "trustpilot-pp-cli"
SEARCH_TIMEOUT = 75 # generous: a cold run may harvest a WAF cookie (~10s).
+AUTH_STATUS_TIMEOUT = 20 # auth status is a local SQLite read; fast.
+
NO_BROWSER_ENV = "LAST30DAYS_TRUSTPILOT_NO_BROWSER"
+# Among name-matching search hits, the top hit must have this many times the
+# runner-up's review volume to win automatically. Lookalike/squatter pages have
+# tiny volume (ThriftBooks: 2.8M vs 130); comparable volume means genuine
+# ambiguity, where falling back beats silently picking the wrong company.
+DOMAIN_DOMINANCE_FACTOR = 50
+
# Domain-like token, e.g. "chownow.com", "nothing.tech".
_DOMAIN_RE = re.compile(r"\b[a-z0-9][a-z0-9-]*\.(com|io|co|net|org|app|ai|dev|gg|tech|shop|store)\b")
@@ -132,6 +154,192 @@ def _build_info_args(identifier: str) -> List[str]:
return [CLI_BIN, "info", identifier, "--agent"]
+def _normalize_name(text: str) -> str:
+ """Case/whitespace/punctuation-insensitive brand-name key."""
+ return re.sub(r"[^a-z0-9]", "", (text or "").lower())
+
+
+# name->domain results, keyed by normalized topic. Per-topic (NOT a single
+# process-wide slot): vs-mode resolves several entities in one process, and a
+# single slot would serve entity A's domain to entity B.
+_domain_cache: Dict[str, Optional[str]] = {}
+_domain_cache_lock = threading.Lock()
+
+_warmup_lock = threading.Lock()
+_warmup_at: Optional[float] = None # time.monotonic() of the last warm-up
+
+# Warm-up freshness window, matching the CLI's ~4-minute safe replay bound for
+# WAF tokens. A boolean-forever flag would leave long-lived host processes
+# running stale (and never retrying a failed login); the TTL re-checks cheaply
+# via `auth status` once the window lapses.
+WARMUP_TTL_SECONDS = 240
+
+
+def _reset_state_for_tests() -> None:
+ """Clear module-level caches/flags (tests only)."""
+ global _warmup_at
+ with _domain_cache_lock:
+ _domain_cache.clear()
+ _warmup_at = None
+
+
+def _warmup_fresh() -> bool:
+ return _warmup_at is not None and (time.monotonic() - _warmup_at) < WARMUP_TTL_SECONDS
+
+
+def _select_search_hit(topic: str, hits: List[Any]) -> Optional[str]:
+ """Pick the canonical domain from search hits, or None when ambiguous.
+
+ Name-match is mandatory: review volume must never override a name
+ mismatch, or the engine attributes another company's reviews to the topic.
+ Among name-matching hits the winner must dominate on review volume
+ (DOMAIN_DOMINANCE_FACTOR); comparable volume is genuine ambiguity and
+ falls back to legacy behavior.
+ """
+ want = _normalize_name(topic)
+ if not want:
+ return None
+ matching: List[tuple[int, str]] = []
+ for hit in hits:
+ if not isinstance(hit, dict):
+ continue
+ domain = str(hit.get("domain") or hit.get("identifyingName") or "").strip()
+ name = str(hit.get("displayName") or hit.get("name") or "").strip()
+ if not domain or _normalize_name(name) != want:
+ continue
+ try:
+ count = int(hit.get("numberOfReviews") or 0)
+ except (TypeError, ValueError):
+ count = 0
+ matching.append((count, domain))
+ if not matching:
+ top = next(
+ (str(h.get("domain") or "").strip() for h in hits
+ if isinstance(h, dict) and h.get("domain")),
+ "",
+ )
+ if top:
+ _log(
+ f"no name-matching search hit; top candidate was '{top}' - "
+ f"pass --trustpilot-domain to target it"
+ )
+ return None
+ matching.sort(reverse=True)
+ if len(matching) == 1:
+ return matching[0][1]
+ top_count, top_domain = matching[0]
+ runner_count, runner_domain = matching[1]
+ if top_count >= max(1, runner_count) * DOMAIN_DOMINANCE_FACTOR:
+ return top_domain
+ _log(
+ f"ambiguous search hits ('{top_domain}' vs '{runner_domain}'); "
+ f"falling back - pass --trustpilot-domain to disambiguate"
+ )
+ return None
+
+
+def _search_domain(topic: str) -> Optional[str]:
+ """Resolve a company name to its Trustpilot domain via the CLI's search.
+
+ Cached per normalized topic (thread-safe), so repeat lookups cost one
+ subprocess while vs-mode entities still resolve independently. Only
+ definitive results are cached: a transient CLI failure (timeout, spawn
+ error, malformed JSON) returns None WITHOUT caching, so one flaky search
+ does not suppress resolution for this topic for the rest of the process.
+ """
+ key = _normalize_name(topic)
+ if not key:
+ return None
+ with _domain_cache_lock:
+ if key in _domain_cache:
+ return _domain_cache[key]
+ data = _run_cli(
+ [CLI_BIN, "search", topic.strip(), "--limit", "5", "--agent"],
+ timeout=SEARCH_TIMEOUT,
+ )
+ if not isinstance(data, dict) or "error" in data:
+ return None # transient failure: retry on the next lookup
+ hits = data.get("hits")
+ if not isinstance(hits, list):
+ # Degenerate payload (e.g. empty stdout parses to {}): not a
+ # definitive no-match -- do not cache, retry on the next lookup.
+ return None
+ domain = _select_search_hit(topic, hits)
+ if domain:
+ _log(f"resolved '{topic}' -> '{domain}' via search")
+ with _domain_cache_lock:
+ _domain_cache[key] = domain
+ return domain
+
+
+def _is_session_fresh(status: Dict[str, Any]) -> bool:
+ """Read the freshness signal from an ``auth status --agent`` payload."""
+ if not isinstance(status, dict) or "error" in status:
+ return False
+ containers: List[Dict[str, Any]] = [status]
+ session = status.get("session")
+ if isinstance(session, dict):
+ containers.append(session)
+ for container in containers:
+ for key in ("isFresh", "fresh"):
+ if key in container:
+ return bool(container[key])
+ return False
+
+
+def ensure_session_ready(
+ topic: str,
+ config: Optional[Dict[str, Any]] = None,
+ has_domain: bool = False,
+) -> None:
+ """Warm the CLI's WAF session, serialized, at the first Trustpilot fetch.
+
+ Called from ``search_trustpilot`` (never from the pipeline's fan-out
+ setup), so it only ever delays the one capped Trustpilot stream, never
+ the other sources -- and never fires for runs whose plan fetches no
+ Trustpilot at all. The module lock serializes concurrent streams (vs-mode
+ fans out up to 6 entity sub-runs) so they never race their own Chrome
+ harvests. Freshness is a monotonic TTL (WARMUP_TTL_SECONDS, matching the
+ CLI's ~4-minute token bound), not a boolean-forever flag: long-lived host
+ processes re-check via ``auth status`` after the window lapses, which
+ also retries a previously failed login. ``auth login`` fires only when
+ ``auth status`` reports the session missing or stale -- login always
+ harvests (~10s Chrome), it has no freshness no-op. Logs only structured
+ status strings; the raw CLI payload carries live WAF-token prefixes and
+ must never be logged. Never raises.
+ """
+ global _warmup_at
+ if _warmup_fresh():
+ return
+ if not _is_available():
+ return
+ if not _harvest_allowed(config):
+ return
+ if not has_domain and not is_brand_shaped(topic):
+ return
+ with _warmup_lock:
+ if _warmup_fresh():
+ return
+ status = _run_cli(
+ [CLI_BIN, "auth", "status", "--agent"], timeout=AUTH_STATUS_TIMEOUT
+ )
+ if _is_session_fresh(status):
+ _log("warm-up: fresh")
+ _warmup_at = time.monotonic()
+ return
+ # Missing session exits non-zero (an error dict here): that is the
+ # "login needed" signal, not a warm-up failure.
+ login = _run_cli([CLI_BIN, "auth", "login", "--agent"], timeout=SEARCH_TIMEOUT)
+ if isinstance(login, dict) and "error" in login:
+ _log("warm-up failed: auth login did not complete")
+ else:
+ _log("warm-up: harvested")
+ # Stamp even on failure: a broken Chrome will not fix itself within
+ # the TTL, per-call CLI auto-harvest remains the fallback, and the
+ # TTL lapse retries the warm-up later.
+ _warmup_at = time.monotonic()
+
+
def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
"""Invoke trustpilot-pp-cli and parse the JSON object. Never raises."""
if not _is_available():
@@ -171,23 +379,66 @@ def search_trustpilot(
to_date: str,
depth: str = "default",
config: Optional[Dict[str, Any]] = None,
+ explicit_domain: Optional[str] = None,
+ domain_is_hint: bool = False,
) -> Dict[str, Any]:
"""Look up a company's Trustpilot sentiment, gated on a brand-shaped topic.
+ ``explicit_domain`` is used verbatim as the CLI identifier and bypasses
+ the brand-shape gate (an explicit domain is proof of brand intent). A
+ user-set domain is verbatim-final; a resolved hint
+ (``domain_is_hint=True``) retries via the CLI search when the lookup
+ misses, since auto-resolve can guess a plausible-but-wrong domain (the
+ official site is not always Trustpilot's canonical identifyingName).
+
+ Without an explicit domain, a bare company name resolves via the CLI's
+ ``search`` (cached per topic) before falling back to the cleaned topic.
+
Returns ``{"results": [info_dict]}`` for a resolved company, or
- ``{"results": []}`` when the topic is not brand-shaped, the browser opt-out
- is set, or the CLI fails.
+ ``{"results": []}`` when the topic is not brand-shaped, the browser
+ opt-out is set, or the CLI fails.
"""
- if not is_brand_shaped(topic):
+ explicit_domain = (explicit_domain or "").strip() or None
+ user_domain = bool(explicit_domain) and not domain_is_hint
+ # Only a USER-set domain proves brand intent and bypasses the brand-shape
+ # gate. An auto-resolved hint must not widen activation beyond
+ # brand-shaped topics, or a generic topic that happens to yield a hint
+ # would trigger a Chrome harvest -- violating the module's documented
+ # "never harvests on non-company topics" contract.
+ if not user_domain and not is_brand_shaped(topic):
return {"results": []}
if not _is_available():
return {"results": [], "error": f"{CLI_BIN} not on PATH"}
if not _harvest_allowed(config):
_log("skipped: browser opt-out set")
return {"results": []}
- identifier = _company_identifier(topic)
+ # Serialized session check at first source touch (all gates above have
+ # passed, so this never fires for topics the source would not fetch).
+ ensure_session_ready(topic, config=config, has_domain=bool(explicit_domain))
+ # Retry-budget timer starts AFTER the warm-up: a slow Chrome harvest must
+ # not consume the hint-retry budget when the info call itself was fast.
+ started = time.monotonic()
+ if explicit_domain:
+ identifier = explicit_domain
+ else:
+ identifier = _company_identifier(topic)
+ if not _DOMAIN_RE.search(topic.lower()):
+ # No domain token in the topic: Trustpilot pages are keyed by
+ # domain, so resolve name -> domain before the info lookup.
+ identifier = _search_domain(topic) or identifier
_log(f"info '{identifier}'")
data = _run_cli(_build_info_args(identifier), timeout=SEARCH_TIMEOUT)
+ if ("error" in data or not data) and explicit_domain and domain_is_hint:
+ # The auto-resolved hint missed. Only user-set flags are
+ # verbatim-final; a hint falls through to the search resolution.
+ # Skip the retry chain when the first lookup already consumed a full
+ # single-call budget (hung CLI) -- one stream must not chain three
+ # sequential SEARCH_TIMEOUT-bound subprocesses.
+ if time.monotonic() - started < SEARCH_TIMEOUT:
+ resolved = _search_domain(topic)
+ if resolved and resolved != identifier:
+ _log(f"hint '{identifier}' missed; retrying via search as '{resolved}'")
+ data = _run_cli(_build_info_args(resolved), timeout=SEARCH_TIMEOUT)
if "error" in data or not data:
return {"results": []}
return {"results": [data]}
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index fbad973c..6e3629e9 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -552,5 +552,46 @@ class CliV3Tests(unittest.TestCase):
)
self.assertIn("[GitHub] Canonicalized repos:", stderr.getvalue())
+ def test_main_passes_trustpilot_domain_to_pipeline_run(self):
+ """The user-set flag must reach pipeline.run verbatim with
+ provenance user-set (is_hint False) on the single-topic path."""
+ report = self.make_report()
+ diag = {
+ "available_sources": ["grounding"],
+ "providers": {"google": True, "openai": False, "xai": False},
+ "x_backend": None,
+ "bird_installed": True,
+ "bird_authenticated": False,
+ "bird_username": None,
+ "native_web_backend": "brave",
+ }
+ with mock.patch.object(cli.env, "get_config", return_value={}), \
+ mock.patch.object(cli.pipeline, "diagnose", return_value=diag), \
+ mock.patch.object(cli.pipeline, "run", return_value=report) as run_mock, \
+ mock.patch.object(cli, "emit_output", return_value="# rendered"), \
+ mock.patch.object(sys, "argv", [
+ "last30days.py",
+ "ThriftBooks",
+ "--trustpilot-domain",
+ "www.thriftbooks.com",
+ ]):
+ stdout = io.StringIO()
+ stderr = io.StringIO()
+ with redirect_stdout(stdout), redirect_stderr(stderr):
+ rc = cli.main()
+ self.assertEqual(0, rc)
+ main_call = next(
+ (c for c in run_mock.call_args_list
+ if c.kwargs.get("trustpilot_domain") == "www.thriftbooks.com"),
+ None,
+ )
+ self.assertIsNotNone(
+ main_call,
+ f"No pipeline.run call carried trustpilot_domain; saw "
+ f"{[c.kwargs.get('trustpilot_domain') for c in run_mock.call_args_list]}",
+ )
+ self.assertFalse(main_call.kwargs.get("trustpilot_domain_is_hint"))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_competitors_plan_threading.py b/tests/test_competitors_plan_threading.py
index 72afdc48..4e0cb6b6 100644
--- a/tests/test_competitors_plan_threading.py
+++ b/tests/test_competitors_plan_threading.py
@@ -143,6 +143,27 @@ class SubrunKwargsForTests(unittest.TestCase):
self.assertIsNone(kwargs["x_related"])
self.assertEqual(kwargs["_context"], "")
+ def test_trustpilot_domain_plan_wins_and_is_not_hint(self):
+ kwargs = cli.subrun_kwargs_for(
+ "ThriftBooks",
+ {"trustpilot_domain": "www.thriftbooks.com"},
+ resolved={"trustpilot_domain": "wrong.com"},
+ )
+ self.assertEqual(kwargs["trustpilot_domain"], "www.thriftbooks.com")
+ self.assertFalse(kwargs["_trustpilot_domain_is_hint"])
+
+ def test_trustpilot_domain_from_auto_resolve_is_hint(self):
+ kwargs = cli.subrun_kwargs_for(
+ "ThriftBooks", {}, resolved={"trustpilot_domain": "thriftbooks.com"},
+ )
+ self.assertEqual(kwargs["trustpilot_domain"], "thriftbooks.com")
+ self.assertTrue(kwargs["_trustpilot_domain_is_hint"])
+
+ def test_trustpilot_domain_absent_is_none(self):
+ kwargs = cli.subrun_kwargs_for("ThriftBooks", {}, resolved={})
+ self.assertIsNone(kwargs["trustpilot_domain"])
+ self.assertFalse(kwargs["_trustpilot_domain_is_hint"])
+
def test_x_handle_strips_at_sign(self):
kwargs = cli.subrun_kwargs_for(
"Drake", {"x_handle": "@Drake"}, resolved={},
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index 11414be5..192985e5 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -357,6 +357,60 @@ class TestThinSourceRetryPlannedSource(unittest.TestCase):
self.assertEqual("https://x.com/example/status/100", bundle.items_by_source["x"][0].url)
+
+class TestTrustpilotNeverRetriedAsThin(unittest.TestCase):
+ @patch("lib.pipeline._retrieve_stream")
+ def test_trustpilot_excluded_from_thin_source_retry(self, mock_retrieve):
+ """Trustpilot returns at most one item by design, so the '<3 items'
+ thinness rule must never re-fetch it: a retry would bypass
+ MAX_SOURCE_FETCHES and re-resolve without the caller's
+ --trustpilot-domain (a lookalike-misattribution path)."""
+ mock_retrieve.return_value = ([], {})
+
+ plan = schema.QueryPlan(
+ intent="product",
+ freshness_mode="balanced_recent",
+ cluster_mode="none",
+ raw_topic="ThriftBooks",
+ subqueries=[
+ schema.SubQuery(
+ label="primary",
+ search_query="thriftbooks",
+ ranking_query="What matters for ThriftBooks?",
+ sources=["trustpilot", "x"],
+ )
+ ],
+ source_weights={"trustpilot": 1.0, "x": 1.0},
+ )
+ bundle = schema.RetrievalBundle(
+ items_by_source={
+ # one successful trustpilot item -- its normal success state,
+ # yet still "<3" and thus retry-eligible without the exclusion
+ "trustpilot": [
+ _make_source_item("trustpilot", "tp1", "https://www.trustpilot.com/review/x.com"),
+ ],
+ }
+ )
+
+ pipeline._retry_thin_sources(
+ topic="ThriftBooks",
+ bundle=bundle,
+ plan=plan,
+ config={},
+ depth="default",
+ date_range=("2026-06-04", "2026-07-04"),
+ runtime=_make_runtime("bird"),
+ mock=False,
+ rate_limited_sources=set(),
+ rate_limit_lock=threading.Lock(),
+ settings=pipeline.DEPTH_SETTINGS["default"],
+ )
+
+ retried = [call.kwargs["source"] for call in mock_retrieve.call_args_list]
+ self.assertNotIn("trustpilot", retried)
+ self.assertIn("x", retried) # other thin sources still retry
+
+
def _make_runtime(x_backend="bird"):
return schema.ProviderRuntime(
reasoning_provider="mock",
diff --git a/tests/test_resolve.py b/tests/test_resolve.py
index 6357e755..a0da63a8 100644
--- a/tests/test_resolve.py
+++ b/tests/test_resolve.py
@@ -359,5 +359,50 @@ class AutoResolveCategoryIntegration(unittest.TestCase):
result = resolve.auto_resolve("test topic", {})
self.assertIsNone(result["category"])
+
+class ExtractOfficialDomainTests(unittest.TestCase):
+ def test_extracts_matching_registrable_domain(self):
+ items = [{"url": "https://www.thriftbooks.com/about-thriftbooks/", "title": "", "snippet": ""}]
+ self.assertEqual(
+ resolve._extract_official_domain("ThriftBooks", items),
+ "thriftbooks.com",
+ )
+
+ def test_skips_platform_hosts(self):
+ items = [
+ {"url": "https://www.reddit.com/r/thriftbooks/", "title": "", "snippet": ""},
+ {"url": "https://x.com/thriftbooks", "title": "", "snippet": ""},
+ ]
+ self.assertEqual(resolve._extract_official_domain("ThriftBooks", items), "")
+
+ def test_non_matching_domain_returns_empty(self):
+ items = [{"url": "https://bookriot.com/thriftbooks-review/", "title": "", "snippet": ""}]
+ self.assertEqual(resolve._extract_official_domain("ThriftBooks", items), "")
+
+ def test_empty_items_returns_empty(self):
+ self.assertEqual(resolve._extract_official_domain("ThriftBooks", []), "")
+
+
+class AutoResolveTrustpilotDomainTests(unittest.TestCase):
+ def test_no_backend_includes_empty_trustpilot_domain(self):
+ result = resolve.auto_resolve("test topic", {})
+ self.assertEqual(result["trustpilot_domain"], "")
+
+ @patch("lib.resolve.grounding.web_search")
+ def test_auto_resolve_fills_trustpilot_domain_from_news(self, mock_search):
+ def side_effect(query, date_range, config):
+ if "news" in query:
+ return [
+ {"title": "ThriftBooks launches challenge",
+ "snippet": "",
+ "url": "https://www.thriftbooks.com/blog/challenge/"},
+ ], {}
+ return [], {}
+
+ mock_search.side_effect = side_effect
+ result = resolve.auto_resolve("ThriftBooks", {"BRAVE_API_KEY": "fake"})
+ self.assertEqual(result["trustpilot_domain"], "thriftbooks.com")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_trustpilot_source.py b/tests/test_trustpilot_source.py
index 277ad331..eee52026 100644
--- a/tests/test_trustpilot_source.py
+++ b/tests/test_trustpilot_source.py
@@ -160,3 +160,317 @@ def test_parse_handles_empty_and_malformed():
assert trustpilot.parse_trustpilot_response({"results": []}, query="x") == []
assert trustpilot.parse_trustpilot_response({}, query="x") == []
assert trustpilot.parse_trustpilot_response({"results": [{}]}, query="x") == []
+
+
+# ---- shared scaffolding for domain-resolution and warm-up tests ----
+
+D1, D2 = "2026-06-01", "2026-06-27"
+
+THRIFTBOOKS_HITS = {
+ "hits": [
+ {"displayName": "ThriftBooks", "domain": "www.thriftbooks.com", "numberOfReviews": 2843175},
+ {"displayName": "Thrift Books", "domain": "thriftbook.com", "numberOfReviews": 130},
+ {"displayName": "Thriftybooks", "domain": "thriftybooks.com", "numberOfReviews": 6},
+ ]
+}
+
+INFO_OK = {"name": "ThriftBooks", "trustScore": 4.5, "reviewCount": 2843175, "aiSummary": "Great."}
+
+
[email protected](autouse=True)
+def _reset_trustpilot_state():
+ trustpilot._reset_state_for_tests()
+ yield
+ trustpilot._reset_state_for_tests()
+
+
+def _capture_cli(monkeypatch, responses):
+ """Mock _run_cli, recording argv. ``responses`` maps a subcommand key
+ ("info", "search", "auth status", "auth login") to a dict, or to a list of
+ dicts consumed in order."""
+ calls: list[list[str]] = []
+
+ def fake(cmd, timeout):
+ calls.append(list(cmd))
+ key = cmd[1] if cmd[1] != "auth" else f"auth {cmd[2]}"
+ resp = responses.get(key, {})
+ if isinstance(resp, list):
+ return dict(resp.pop(0)) if resp else {}
+ return dict(resp)
+
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(trustpilot, "_run_cli", fake)
+ return calls
+
+
+def _info_args(calls):
+ return [c for c in calls if c[1] == "info"]
+
+
+def _search_args(calls):
+ return [c for c in calls if c[1] == "search"]
+
+
+# ---- explicit domain (--trustpilot-domain) ----
+
+def test_explicit_domain_used_verbatim(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"info": INFO_OK})
+ out = trustpilot.search_trustpilot(
+ "ThriftBooks", D1, D2, explicit_domain="www.thriftbooks.com")
+ assert out["results"][0]["name"] == "ThriftBooks"
+ assert _info_args(calls)[0][2] == "www.thriftbooks.com"
+ assert _search_args(calls) == [] # flag set -> no search call fires
+
+
+def test_explicit_domain_bypasses_brand_gate(monkeypatch):
+ # A 4-word topic fails is_brand_shaped, but an explicit domain is proof
+ # of brand intent -- the CLI must still be invoked with the flag value.
+ calls = _capture_cli(monkeypatch, {"info": INFO_OK})
+ out = trustpilot.search_trustpilot(
+ "Stanley Steemer carpet cleaning", D1, D2,
+ explicit_domain="stanleysteemer.com")
+ assert len(out["results"]) == 1
+ assert _info_args(calls)[0][2] == "stanleysteemer.com"
+
+
+def test_explicit_domain_beats_domain_shaped_topic(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"info": INFO_OK})
+ trustpilot.search_trustpilot(
+ "chownow.com", D1, D2, explicit_domain="www.thriftbooks.com")
+ assert _info_args(calls)[0][2] == "www.thriftbooks.com"
+
+
+def test_user_domain_is_verbatim_final_no_retry(monkeypatch):
+ # User-set flag (domain_is_hint=False): a miss degrades, never re-resolves.
+ calls = _capture_cli(monkeypatch, {"info": {"error": "HTTP 404"}})
+ out = trustpilot.search_trustpilot(
+ "ThriftBooks", D1, D2, explicit_domain="thriftbook.com")
+ assert out == {"results": []}
+ assert _search_args(calls) == []
+
+
+def test_hint_domain_retries_via_search_on_miss(monkeypatch):
+ # Auto-resolved hint (domain_is_hint=True): a 404 falls through to the
+ # CLI search resolution and retries with the canonical domain.
+ calls = _capture_cli(monkeypatch, {
+ "info": [{"error": "HTTP 404"}, INFO_OK],
+ "search": THRIFTBOOKS_HITS,
+ })
+ out = trustpilot.search_trustpilot(
+ "ThriftBooks", D1, D2,
+ explicit_domain="getthriftbooks.io", domain_is_hint=True)
+ assert len(out["results"]) == 1
+ infos = _info_args(calls)
+ assert infos[0][2] == "getthriftbooks.io"
+ assert infos[1][2] == "www.thriftbooks.com"
+
+
+# ---- name -> domain search fallback ----
+
+def test_bare_name_resolves_via_search(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"search": THRIFTBOOKS_HITS, "info": INFO_OK})
+ out = trustpilot.search_trustpilot("ThriftBooks", D1, D2)
+ assert len(out["results"]) == 1
+ assert _search_args(calls)[0][2] == "ThriftBooks"
+ assert _info_args(calls)[0][2] == "www.thriftbooks.com"
+
+
+def test_ambiguous_hits_fall_back_to_topic(monkeypatch):
+ # Two same-named companies with comparable volume: review count must never
+ # break the tie (silent misattribution is worse than a visible miss).
+ hits = {"hits": [
+ {"displayName": "Mercury", "domain": "mercury.com", "numberOfReviews": 50000},
+ {"displayName": "Mercury", "domain": "mercuryinsurance.com", "numberOfReviews": 40000},
+ ]}
+ calls = _capture_cli(monkeypatch, {"search": hits, "info": INFO_OK})
+ trustpilot.search_trustpilot("Mercury", D1, D2)
+ assert _info_args(calls)[0][2] == "Mercury" # legacy fallback identifier
+
+
+def test_review_count_never_overrides_name_mismatch(monkeypatch):
+ hits = {"hits": [
+ {"displayName": "Bolt Technology", "domain": "bolt.eu", "numberOfReviews": 900000},
+ ]}
+ calls = _capture_cli(monkeypatch, {"search": hits, "info": INFO_OK})
+ trustpilot.search_trustpilot("Bolt", D1, D2)
+ assert _info_args(calls)[0][2] == "Bolt"
+
+
+def test_search_error_falls_back_to_topic(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"search": {"error": "boom"}, "info": INFO_OK})
+ out = trustpilot.search_trustpilot("ChowNow", D1, D2)
+ assert len(out["results"]) == 1
+ assert _info_args(calls)[0][2] == "ChowNow"
+
+
+def test_domain_shaped_topic_never_searches(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"info": INFO_OK})
+ trustpilot.search_trustpilot("chownow.com", D1, D2)
+ assert _search_args(calls) == []
+ assert _info_args(calls)[0][2] == "chownow.com"
+
+
+def test_search_cached_per_topic_not_per_process(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"search": dict(THRIFTBOOKS_HITS), "info": INFO_OK})
+ trustpilot.search_trustpilot("ThriftBooks", D1, D2)
+ trustpilot.search_trustpilot("ThriftBooks", D1, D2)
+ assert len(_search_args(calls)) == 1 # repeat topic hits the cache
+
+ # A DIFFERENT topic must trigger its own search (vs-mode entities resolve
+ # independently; a single process-wide slot would cross-contaminate).
+ responses_seen = _search_args(calls)
+ trustpilot.search_trustpilot("ChowNow", D1, D2)
+ assert len(_search_args(calls)) == len(responses_seen) + 1
+
+
+# ---- session warm-up (ensure_session_ready) ----
+
+def test_warmup_fresh_session_skips_login(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True, "hasSession": True}})
+ trustpilot.ensure_session_ready("ThriftBooks")
+ assert [c[2] for c in calls if c[1] == "auth"] == ["status"]
+
+
+def test_warmup_stale_session_logs_in_once(monkeypatch):
+ calls = _capture_cli(monkeypatch, {
+ "auth status": {"error": "no session"},
+ "auth login": {"ok": True},
+ })
+ trustpilot.ensure_session_ready("ThriftBooks")
+ trustpilot.ensure_session_ready("ThriftBooks") # idempotent: no second pass
+ auth_calls = [c[2] for c in calls if c[1] == "auth"]
+ assert auth_calls == ["status", "login"]
+
+
+def test_warmup_concurrent_calls_single_warmup(monkeypatch):
+ import threading as _threading
+ calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True}})
+ threads = [
+ _threading.Thread(target=trustpilot.ensure_session_ready, args=("ThriftBooks",))
+ for _ in range(8)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert len([c for c in calls if c[1] == "auth"]) == 1 # vs-mode race guard
+
+
+def test_warmup_skips_non_brand_topic(monkeypatch):
+ # AE6: generic topic with trustpilot active -> no warm-up, no Chrome.
+ calls = _capture_cli(monkeypatch, {})
+ trustpilot.ensure_session_ready("AI coding agents")
+ assert calls == []
+
+
+def test_warmup_domain_bypasses_brand_gate(monkeypatch):
+ calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True}})
+ trustpilot.ensure_session_ready("Stanley Steemer carpet cleaning", has_domain=True)
+ assert len(calls) == 1
+
+
+def test_warmup_respects_browser_opt_out(monkeypatch):
+ calls = _capture_cli(monkeypatch, {})
+ trustpilot.ensure_session_ready("ThriftBooks", config={trustpilot.NO_BROWSER_ENV: "1"})
+ assert calls == []
+
+
+def test_warmup_failure_never_raises(monkeypatch):
+ calls = _capture_cli(monkeypatch, {
+ "auth status": {"error": "no session"},
+ "auth login": {"error": "chrome missing"},
+ })
+ trustpilot.ensure_session_ready("ThriftBooks") # must not raise
+ assert [c[2] for c in calls if c[1] == "auth"] == ["status", "login"]
+
+
+def test_warmup_logs_no_token_bytes(monkeypatch):
+ # The auth status payload carries live WAF-token prefixes; log lines must
+ # only ever contain structured status strings.
+ logged: list[str] = []
+ monkeypatch.setattr(trustpilot, "_log", lambda msg: logged.append(msg))
+ _capture_cli(monkeypatch, {
+ "auth status": {"isFresh": False, "tokenPrefix": "48372fee-99b"},
+ "auth login": {"ok": True, "token": "48372fee-99b1-dead-beef"},
+ })
+ trustpilot.ensure_session_ready("ThriftBooks")
+ assert logged and all("48372fee" not in msg for msg in logged)
+
+
+def test_trustpilot_capped_to_single_fetch():
+ # N subqueries listing trustpilot must produce exactly one stream: every
+ # stream would use the identical company identifier, and each extra one
+ # risks its own WAF-cookie Chrome harvest.
+ assert pipeline.MAX_SOURCE_FETCHES.get("trustpilot") == 1
+
+
+# ---- review-driven hardening ----
+
+def test_search_trustpilot_warms_session_at_first_touch(monkeypatch):
+ # The warm-up runs inside the source fetch (never the pipeline fan-out
+ # setup), so it must precede the info call within one search invocation.
+ calls = _capture_cli(monkeypatch, {
+ "auth status": {"isFresh": True},
+ "info": INFO_OK,
+ })
+ trustpilot.search_trustpilot(
+ "ThriftBooks", D1, D2, explicit_domain="www.thriftbooks.com")
+ assert calls[0][1] == "auth" and calls[0][2] == "status"
+ assert [c for c in calls if c[1] == "info"]
+
+
+def test_warmup_ttl_lapse_rechecks(monkeypatch):
+ import time as _time
+ calls = _capture_cli(monkeypatch, {"auth status": {"isFresh": True}})
+ trustpilot.ensure_session_ready("ThriftBooks")
+ assert len(calls) == 1
+ # Within the TTL: no re-check.
+ trustpilot.ensure_session_ready("ThriftBooks")
+ assert len(calls) == 1
+ # After the TTL lapses (long-lived host process): cheap re-check fires.
+ trustpilot._warmup_at = _time.monotonic() - (trustpilot.WARMUP_TTL_SECONDS + 1)
+ trustpilot.ensure_session_ready("ThriftBooks")
+ assert len(calls) == 2
+
+
+def test_hint_on_non_brand_topic_stays_quiet(monkeypatch):
+ # An auto-resolved hint must not widen activation beyond brand-shaped
+ # topics -- only a USER-set domain proves brand intent (AE6 contract).
+ calls = _capture_cli(monkeypatch, {})
+ out = trustpilot.search_trustpilot(
+ "AI coding agents", D1, D2,
+ explicit_domain="aicodingagents.com", domain_is_hint=True)
+ assert out == {"results": []}
+ assert calls == []
+
+
+def test_transient_search_error_not_cached(monkeypatch):
+ # A flaky search must not poison the per-topic cache for the process.
+ calls = _capture_cli(monkeypatch, {
+ "search": [{"error": "timeout"}, dict(THRIFTBOOKS_HITS)],
+ "info": INFO_OK,
+ })
+ assert trustpilot._search_domain("ThriftBooks") is None
+ assert trustpilot._search_domain("ThriftBooks") == "www.thriftbooks.com"
+ assert len(_search_args(calls)) == 2
+
+
+def test_empty_search_payload_not_cached(monkeypatch):
+ # Empty stdout parses to {} (exit 0, no output): a degenerate payload,
+ # not a definitive no-match -- it must not become a permanent cache entry.
+ calls = _capture_cli(monkeypatch, {
+ "search": [{}, dict(THRIFTBOOKS_HITS)],
+ "info": INFO_OK,
+ })
+ assert trustpilot._search_domain("ThriftBooks") is None
+ assert trustpilot._search_domain("ThriftBooks") == "www.thriftbooks.com"
+ assert len(_search_args(calls)) == 2
+
+
+def test_definitive_no_match_is_cached(monkeypatch):
+ # A well-formed empty hits list IS definitive: cache it so repeat lookups
+ # for a name Trustpilot does not know cost one subprocess, not N.
+ calls = _capture_cli(monkeypatch, {"search": {"hits": []}, "info": INFO_OK})
+ assert trustpilot._search_domain("ChowNow") is None
+ assert trustpilot._search_domain("ChowNow") is None
+ assert len(_search_args(calls)) == 1