| 1 | """Auto-resolve subreddits, X handles, and current events context for a topic. |
| 2 | |
| 3 | Uses web search (Brave/Exa/Serper/Parallel) to discover relevant communities and context |
| 4 | before the planner runs. This is the engine-side equivalent of SKILL.md Steps |
| 5 | 0.55/0.75 which use Claude Code's WebSearch tool. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import re |
| 11 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 12 | from datetime import datetime, timezone |
| 13 | from html.parser import HTMLParser |
| 14 | from typing import Optional |
| 15 | from urllib.parse import urlsplit |
| 16 | |
| 17 | from . import categories, dates, grounding, http, log, public_host |
| 18 | |
| 19 | MAX_SUBS = 10 |
| 20 | |
| 21 | |
| 22 | def _log(msg: str) -> None: |
| 23 | log.source_log("Resolve", msg, tty_only=False) |
| 24 | |
| 25 | |
| 26 | def _merge_category_peers(topic: str, subreddits: list[str]) -> tuple[list[str], Optional[str]]: |
| 27 | """Extend the WebSearch-extracted subreddit list with category peers. |
| 28 | |
| 29 | Classifies the topic, fetches the category's peer subs, dedupes |
| 30 | case-insensitively against the existing list, and appends missing |
| 31 | peers in priority order. Caps the final list at MAX_SUBS, preserving |
| 32 | every WebSearch-returned sub (they are the freshest signal) and |
| 33 | trimming from the peer-additions end. |
| 34 | |
| 35 | Returns a tuple of (merged_subs, matched_category_id_or_None). |
| 36 | Emits a [Resolve] Matched category log line only when peers were |
| 37 | actually added (not when every peer was already in the WebSearch set). |
| 38 | |
| 39 | Classification failures degrade to "no match" — the unwidened list |
| 40 | is returned and a warning is logged. |
| 41 | """ |
| 42 | try: |
| 43 | category = categories.detect_category(topic) |
| 44 | except Exception as exc: |
| 45 | _log(f"Category classification failed: {exc}") |
| 46 | return list(subreddits)[:MAX_SUBS], None |
| 47 | |
| 48 | if category is None: |
| 49 | return list(subreddits)[:MAX_SUBS], None |
| 50 | |
| 51 | peers = categories.peer_subs_for(category) |
| 52 | if not peers: |
| 53 | return list(subreddits)[:MAX_SUBS], category |
| 54 | |
| 55 | existing_lower = {s.lower() for s in subreddits} |
| 56 | merged = list(subreddits) |
| 57 | added: list[str] = [] |
| 58 | for peer in peers: |
| 59 | if len(merged) >= MAX_SUBS: |
| 60 | break |
| 61 | if peer.lower() in existing_lower: |
| 62 | continue |
| 63 | merged.append(peer) |
| 64 | existing_lower.add(peer.lower()) |
| 65 | added.append(peer) |
| 66 | |
| 67 | if added: |
| 68 | _log(f"Matched category={category}, adding peers: {', '.join(added)}") |
| 69 | |
| 70 | return merged, category |
| 71 | |
| 72 | |
| 73 | def _has_backend(config: dict) -> bool: |
| 74 | """Require a configured search API; the keyless floor is not peer discovery.""" |
| 75 | return grounding.configured_backend(config) is not None |
| 76 | |
| 77 | |
| 78 | # Prose URL / mention path-segment terminator: allows next path segment (/), |
| 79 | # query/fragment (?/#), whitespace, end-of-string, prose delimiters, or a |
| 80 | # trailing sentence period NOT followed by another URL path character. Rejects |
| 81 | # dotted segments like "github.com/team.example/project" or "@alice.bsky.social". |
| 82 | _PROSE_SEG_END = r"(?=[/?#\s)\]\"'\u2019\u201d`,;:!]|$|\.(?=$|[\s)\]\"'\u2019\u201d`,;:!?]))" |
| 83 | |
| 84 | _REDDIT_URL_SUBREDDIT_RE = re.compile( |
| 85 | r"^(?:https?://)?(?:[A-Za-z0-9-]+\.)*reddit\.com/r/([A-Za-z0-9_]{2,21})(?=[/?#]|$)", |
| 86 | re.IGNORECASE, |
| 87 | ) |
| 88 | _TEXT_SUBREDDIT_RE = re.compile( |
| 89 | r"(?:(?i:(?<![A-Za-z0-9./-])(?:https?://)?(?:[a-z0-9-]+\.)*reddit\.com/r/)" |
| 90 | rf"|(?:^|(?<=[\s(\[\"'`\u2018\u201c,]))/?r/)([A-Za-z0-9_]{{2,21}}){_PROSE_SEG_END}" |
| 91 | ) |
| 92 | _X_MENTION_RE = re.compile( |
| 93 | rf"(?<![A-Za-z0-9_.+-])@([A-Za-z0-9_]{{1,15}}){_PROSE_SEG_END}" |
| 94 | ) |
| 95 | _X_URL_HANDLE_RE = re.compile( |
| 96 | r"^(?:https?://)?(?:www\.|mobile\.)?(?:twitter|x)\.com/([A-Za-z0-9_]{1,15})(?:/|$|\?|#)", |
| 97 | re.IGNORECASE, |
| 98 | ) |
| 99 | _GITHUB_URL_USER_RE = re.compile( |
| 100 | r"^(?:https?://)?(?:www\.)?github\.com/([A-Za-z0-9_-]{1,39})(?:/|$|\?|#)", |
| 101 | re.IGNORECASE, |
| 102 | ) |
| 103 | _GITHUB_TEXT_USER_RE = re.compile( |
| 104 | rf"(?<![A-Za-z0-9./-])(?:https?://)?(?:www\.)?github\.com/([A-Za-z0-9_-]{{1,39}}){_PROSE_SEG_END}", |
| 105 | re.IGNORECASE, |
| 106 | ) |
| 107 | _GITHUB_URL_REPO_RE = re.compile( |
| 108 | r"^(?:https?://)?(?:www\.)?github\.com/([A-Za-z0-9_-]{1,39}/[A-Za-z0-9_.-]*[A-Za-z0-9_-])(?:/|$|\?|#)", |
| 109 | re.IGNORECASE, |
| 110 | ) |
| 111 | _GITHUB_TEXT_REPO_RE = re.compile( |
| 112 | rf"(?<![A-Za-z0-9./-])(?:https?://)?(?:www\.)?github\.com/([A-Za-z0-9_-]{{1,39}}/[A-Za-z0-9_.-]*[A-Za-z0-9_-]){_PROSE_SEG_END}", |
| 113 | re.IGNORECASE, |
| 114 | ) |
| 115 | |
| 116 | |
| 117 | def _extract_subreddits(items: list[dict]) -> list[str]: |
| 118 | """Parse subreddit names from search result titles, snippets, and Reddit URLs.""" |
| 119 | seen: set[str] = set() |
| 120 | results: list[str] = [] |
| 121 | for item in items: |
| 122 | text = f"{item.get('title') or ''} {item.get('snippet') or ''}" |
| 123 | url = str(item.get("url") or "").strip() |
| 124 | for match in _TEXT_SUBREDDIT_RE.findall(text): |
| 125 | lower = match.lower() |
| 126 | if lower not in seen: |
| 127 | seen.add(lower) |
| 128 | results.append(match) |
| 129 | for match in _REDDIT_URL_SUBREDDIT_RE.findall(url): |
| 130 | lower = match.lower() |
| 131 | if lower not in seen: |
| 132 | seen.add(lower) |
| 133 | results.append(match) |
| 134 | return results |
| 135 | |
| 136 | |
| 137 | def _extract_x_handle(items: list[dict]) -> str: |
| 138 | """Extract the most likely X/Twitter handle from search results.""" |
| 139 | counts: dict[str, int] = {} |
| 140 | for item in items: |
| 141 | text = f"{item.get('title') or ''} {item.get('snippet') or ''}" |
| 142 | url = str(item.get("url") or "").strip() |
| 143 | for match in _X_MENTION_RE.findall(text): |
| 144 | lower = match.lower() |
| 145 | counts[lower] = counts.get(lower, 0) + 1 |
| 146 | for match in _X_URL_HANDLE_RE.findall(url): |
| 147 | lower = match.lower() |
| 148 | # URL matches are stronger signals |
| 149 | counts[lower] = counts.get(lower, 0) + 3 |
| 150 | # Filter out generic handles |
| 151 | skip = {"twitter", "x", "search", "hashtag", "intent", "share", "i", "home", "explore", "settings"} |
| 152 | counts = {k: v for k, v in counts.items() if k not in skip} |
| 153 | if not counts: |
| 154 | return "" |
| 155 | return max(counts, key=counts.get) |
| 156 | |
| 157 | |
| 158 | def _extract_github_user(items: list[dict]) -> str: |
| 159 | """Extract GitHub username from search results.""" |
| 160 | counts: dict[str, int] = {} |
| 161 | for item in items: |
| 162 | url = str(item.get("url") or "").strip() |
| 163 | text = f"{item.get('title') or ''} {item.get('snippet') or ''}" |
| 164 | for match in _GITHUB_URL_USER_RE.findall(url): |
| 165 | lower = match.lower() |
| 166 | counts[lower] = counts.get(lower, 0) + 3 |
| 167 | for match in _GITHUB_TEXT_USER_RE.findall(text): |
| 168 | lower = match.lower() |
| 169 | counts[lower] = counts.get(lower, 0) + 1 |
| 170 | # Filter out org/repo-like names and generic pages |
| 171 | skip = {"topics", "explore", "settings", "orgs", "search", "features", "about", "pricing", "enterprise"} |
| 172 | counts = {k: v for k, v in counts.items() if k not in skip} |
| 173 | if not counts: |
| 174 | return "" |
| 175 | return max(counts, key=counts.get) |
| 176 | |
| 177 | |
| 178 | # Hosts that can never be a brand's own site; their presence in results is |
| 179 | # platform noise, not an official-domain signal. |
| 180 | _PLATFORM_HOSTS = { |
| 181 | "reddit.com", "x.com", "twitter.com", "github.com", "youtube.com", |
| 182 | "facebook.com", "instagram.com", "tiktok.com", "linkedin.com", |
| 183 | "wikipedia.org", "medium.com", "trustpilot.com", "crunchbase.com", |
| 184 | "bloomberg.com", "apple.com", "play.google.com", "google.com", |
| 185 | "threads.com", "pinterest.com", "glassdoor.com", "indeed.com", |
| 186 | "news.ycombinator.com", "substack.com", "amazon.com", "ebay.com", |
| 187 | } |
| 188 | |
| 189 | |
| 190 | _RESERVED_HOST_SUFFIXES = frozenset({"localhost", "local", "internal", "localdomain", "arpa"}) |
| 191 | _VALID_DOMAIN_RE = re.compile( |
| 192 | r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+" |
| 193 | ) |
| 194 | _VALID_TLD_RE = re.compile(r"[a-z]{2,63}|xn--[a-z0-9-]{2,59}") |
| 195 | _URL_TOKEN_RE = re.compile(r"https?://[^\s\"'<>)\]]+", re.IGNORECASE) |
| 196 | |
| 197 | |
| 198 | def _public_site_host(site: str) -> str: |
| 199 | """Return a validated public DNS hostname from a domain or http(s) URL, or ''.""" |
| 200 | if not isinstance(site, str): |
| 201 | return "" |
| 202 | text = site.strip() |
| 203 | if not text or "\\" in text or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text): |
| 204 | return "" |
| 205 | if "://" in text: |
| 206 | candidate = text |
| 207 | else: |
| 208 | if text.startswith("//"): |
| 209 | return "" |
| 210 | candidate = f"https://{text}" |
| 211 | try: |
| 212 | parsed = urlsplit(candidate) |
| 213 | port = parsed.port |
| 214 | except ValueError: |
| 215 | return "" |
| 216 | scheme = parsed.scheme.lower() |
| 217 | if scheme not in ("http", "https"): |
| 218 | return "" |
| 219 | if parsed.username is not None or parsed.password is not None: |
| 220 | return "" |
| 221 | if not parsed.netloc.isascii() or "%" in parsed.netloc: |
| 222 | return "" |
| 223 | if port is not None and not ( |
| 224 | (scheme == "https" and port == 443) or (scheme == "http" and port == 80) |
| 225 | ): |
| 226 | return "" |
| 227 | host = (parsed.hostname or "").strip().lower().rstrip(".") |
| 228 | if not host or not _VALID_DOMAIN_RE.fullmatch(host): |
| 229 | return "" |
| 230 | if public_host._parse_ip_literal(host) is not None: |
| 231 | return "" |
| 232 | labels = host.split(".") |
| 233 | if host == "localhost" or labels[-1] in _RESERVED_HOST_SUFFIXES: |
| 234 | return "" |
| 235 | if not _VALID_TLD_RE.fullmatch(labels[-1]): |
| 236 | return "" |
| 237 | if not public_host.is_public_address_syntax(f"https://{host}/"): |
| 238 | return "" |
| 239 | return host |
| 240 | |
| 241 | |
| 242 | def _official_site_redirect_guard(target: str) -> bool: |
| 243 | return bool(public_host.is_public_address_syntax(target) and _public_site_host(target)) |
| 244 | |
| 245 | |
| 246 | def _extract_official_domain(topic: str, items: list[dict]) -> str: |
| 247 | """Extract the brand's own domain from search-result URLs. |
| 248 | |
| 249 | Conservative on purpose: only a hostname whose registrable label |
| 250 | normalizes to the topic name qualifies ("ThriftBooks" -> thriftbooks.com). |
| 251 | This feeds Trustpilot targeting as a HINT (the engine retries via the |
| 252 | CLI's own search when the hint misses), so a miss here is cheap and a |
| 253 | wrong guess is recoverable. |
| 254 | """ |
| 255 | want = re.sub(r"[^a-z0-9]", "", topic.lower()) |
| 256 | if not want: |
| 257 | return "" |
| 258 | for item in items: |
| 259 | for source in [item.get("url", ""), f"{item.get('title', '')} {item.get('snippet', '')}"]: |
| 260 | for raw_url in _URL_TOKEN_RE.findall(source or ""): |
| 261 | host = _public_site_host(raw_url.rstrip(".,;:!?")) |
| 262 | if not host: |
| 263 | continue |
| 264 | bare = host.removeprefix("www.") |
| 265 | if any(bare == p or bare.endswith("." + p) for p in _PLATFORM_HOSTS): |
| 266 | continue |
| 267 | labels = bare.split(".") |
| 268 | if len(labels) < 2: |
| 269 | continue |
| 270 | is_ccsld = labels[-2] in ("co", "com") and len(labels[-1]) == 2 and len(labels) >= 3 |
| 271 | registrable = labels[-3] if is_ccsld else labels[-2] |
| 272 | if re.sub(r"[^a-z0-9]", "", registrable) == want: |
| 273 | return bare |
| 274 | return "" |
| 275 | |
| 276 | |
| 277 | # Profile links only: x.com/{handle} with nothing after the handle but a slash, |
| 278 | # query or fragment. /status/, /intent/ and /share links name someone else's |
| 279 | # post or a share widget, never the site's own account. |
| 280 | _X_PROFILE_LINK = re.compile( |
| 281 | r"^(?:https?:)?//(?:www\.|mobile\.)?(?:x|twitter)\.com/([A-Za-z0-9_]{1,15})/?(?:[?#].*)?$", |
| 282 | re.IGNORECASE, |
| 283 | ) |
| 284 | _GITHUB_OWNER_LINK = re.compile( |
| 285 | r"^(?:https?:)?//(?:www\.)?github\.com/([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))(?:[/?#].*)?$", |
| 286 | re.IGNORECASE, |
| 287 | ) |
| 288 | _X_NON_ACCOUNTS = { |
| 289 | "twitter", "x", "search", "hashtag", "intent", "share", "i", "home", |
| 290 | "explore", "settings", "login", "signup", "tos", "privacy", "messages", |
| 291 | "notifications", "compose", |
| 292 | } |
| 293 | _GITHUB_NON_OWNERS = { |
| 294 | "topics", "explore", "settings", "orgs", "search", "features", "about", |
| 295 | "pricing", "enterprise", "login", "join", "sponsors", "marketplace", |
| 296 | "apps", "collections", "trending", "site", "security", "customer-stories", |
| 297 | } |
| 298 | |
| 299 | |
| 300 | def _official_site_url(site: str) -> str: |
| 301 | """Normalize a domain or URL to the site's homepage URL, or "".""" |
| 302 | host = _public_site_host(site) |
| 303 | return f"https://{host}/" if host else "" |
| 304 | |
| 305 | |
| 306 | _CHROME_TAGS = frozenset({"header", "footer", "nav"}) |
| 307 | _MAX_OFFICIAL_SITE_HTML_BYTES = 1 * 1024 * 1024 |
| 308 | |
| 309 | |
| 310 | class _SocialLinkParser(HTMLParser): |
| 311 | """Single-pass O(N) HTML link extractor tracking header/footer/nav depth.""" |
| 312 | |
| 313 | def __init__(self) -> None: |
| 314 | super().__init__(convert_charrefs=True) |
| 315 | self._chrome_depths = {tag: 0 for tag in _CHROME_TAGS} |
| 316 | self._chrome_active = 0 |
| 317 | self.hrefs: list[tuple[str, bool]] = [] |
| 318 | |
| 319 | def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: |
| 320 | tag_lower = tag.lower() |
| 321 | if tag_lower in _CHROME_TAGS: |
| 322 | self._chrome_depths[tag_lower] += 1 |
| 323 | self._chrome_active += 1 |
| 324 | in_chrome = self._chrome_active > 0 |
| 325 | for name, value in attrs: |
| 326 | if name.lower() == "href" and value: |
| 327 | href = value.strip() |
| 328 | if href: |
| 329 | self.hrefs.append((href, in_chrome)) |
| 330 | |
| 331 | def handle_endtag(self, tag: str) -> None: |
| 332 | tag_lower = tag.lower() |
| 333 | if tag_lower in _CHROME_TAGS and self._chrome_depths[tag_lower] > 0: |
| 334 | self._chrome_depths[tag_lower] -= 1 |
| 335 | self._chrome_active -= 1 |
| 336 | |
| 337 | |
| 338 | def _extract_homepage_hrefs(html_text: str) -> list[tuple[str, bool]]: |
| 339 | """Extract (href, in_chrome) pairs from homepage HTML in a single linear pass.""" |
| 340 | if not html_text: |
| 341 | return [] |
| 342 | parser = _SocialLinkParser() |
| 343 | parser.feed(html_text[:_MAX_OFFICIAL_SITE_HTML_BYTES]) |
| 344 | parser.close() |
| 345 | return parser.hrefs |
| 346 | |
| 347 | |
| 348 | def _site_label(url: str) -> str: |
| 349 | """The registrable label of a homepage URL: https://www.typesafe.ai/ -> typesafe.""" |
| 350 | labels = url.split("://", 1)[-1].strip("/").split(":")[0].split(".") |
| 351 | labels = [label for label in labels if label not in {"www", "m"}] |
| 352 | return re.sub(r"[^a-z0-9]", "", labels[0].lower()) if labels else "" |
| 353 | |
| 354 | |
| 355 | def _own_account(links: list[tuple[str, bool]], site_label: str) -> str: |
| 356 | """The site's own account among its profile links, or "" when ambiguous. |
| 357 | |
| 358 | A homepage also links customers, testimonials, and dependencies, so |
| 359 | link counts and page order cannot tell the site's account from someone |
| 360 | else's. Accept an account only when it is the sole one linked, the sole |
| 361 | one in the page's header/footer/nav, or the sole one named after the site. |
| 362 | """ |
| 363 | # X and GitHub names are case-insensitive: TypeSafeAI and typesafeai are |
| 364 | # one account. Keep the first spelling the page uses. |
| 365 | spelling: dict[str, str] = {} |
| 366 | for name, _ in links: |
| 367 | spelling.setdefault(name.lower(), name) |
| 368 | distinct = list(spelling.values()) |
| 369 | if len(distinct) <= 1: |
| 370 | return distinct[0] if distinct else "" |
| 371 | chrome = list(dict.fromkeys(spelling[name.lower()] for name, in_chrome in links if in_chrome)) |
| 372 | if len(chrome) == 1: |
| 373 | return chrome[0] |
| 374 | named = [ |
| 375 | name for name in (chrome or distinct) |
| 376 | if site_label and len(site_label) >= 3 |
| 377 | and site_label in re.sub(r"[^a-z0-9]", "", name.lower()) |
| 378 | ] |
| 379 | return named[0] if len(named) == 1 else "" |
| 380 | |
| 381 | |
| 382 | def official_site_socials(site: str, *, timeout: int = 10) -> dict[str, str]: |
| 383 | """Read a brand's own X and GitHub accounts from its homepage links. |
| 384 | |
| 385 | A company's homepage links its own accounts (usually in the header or |
| 386 | footer), so this is the most reliable first-party source for the handle, |
| 387 | and it needs no search key. Only ``href`` targets count: a handle quoted |
| 388 | in page copy may be anyone's. Returns ``{"x_handle": ..., "github_user": |
| 389 | ...}`` with "" for any account the page does not link, and both empty |
| 390 | when the page cannot be fetched. |
| 391 | """ |
| 392 | result = {"x_handle": "", "github_user": ""} |
| 393 | url = _official_site_url(site) |
| 394 | if not url or not public_host.is_public_address_syntax(url): |
| 395 | return result |
| 396 | try: |
| 397 | html, url = http.text_on_either_host_form( |
| 398 | lambda page: http.get_text( |
| 399 | page, |
| 400 | timeout=timeout, |
| 401 | retries=1, |
| 402 | accept="text/html", |
| 403 | public_only=True, |
| 404 | redirect_guard=_official_site_redirect_guard, |
| 405 | max_bytes=_MAX_OFFICIAL_SITE_HTML_BYTES, |
| 406 | decode_errors="replace", |
| 407 | ), |
| 408 | url, |
| 409 | ) |
| 410 | except (UnicodeDecodeError, ValueError) as exc: |
| 411 | _log(f"Official site {url} could not be fetched: {exc}") |
| 412 | return result |
| 413 | if not html: |
| 414 | _log(f"Official site {url} could not be fetched") |
| 415 | return result |
| 416 | x_links: list[tuple[str, bool]] = [] |
| 417 | github_links: list[tuple[str, bool]] = [] |
| 418 | for href, in_chrome in _extract_homepage_hrefs(html): |
| 419 | x_match = _X_PROFILE_LINK.match(href) |
| 420 | if x_match and x_match.group(1).lower() not in _X_NON_ACCOUNTS: |
| 421 | x_links.append((x_match.group(1), in_chrome)) |
| 422 | continue |
| 423 | gh_match = _GITHUB_OWNER_LINK.match(href) |
| 424 | if gh_match and gh_match.group(1).lower() not in _GITHUB_NON_OWNERS: |
| 425 | github_links.append((gh_match.group(1), in_chrome)) |
| 426 | label = _site_label(url) |
| 427 | result["x_handle"] = _own_account(x_links, label) |
| 428 | result["github_user"] = _own_account(github_links, label) |
| 429 | _log( |
| 430 | f"Official site {url}: x_handle={result['x_handle']!r}, " |
| 431 | f"github_user={result['github_user']!r}" |
| 432 | ) |
| 433 | return result |
| 434 | |
| 435 | |
| 436 | def _extract_github_repos(items: list[dict]) -> list[str]: |
| 437 | """Extract owner/repo strings from search results.""" |
| 438 | skip_owners = {"topics", "explore", "settings", "orgs", "search", "features", "about", "pricing", "enterprise"} |
| 439 | seen: set[str] = set() |
| 440 | repos: list[str] = [] |
| 441 | for item in items: |
| 442 | url = str(item.get("url") or "").strip() |
| 443 | text = f"{item.get('title') or ''} {item.get('snippet') or ''}" |
| 444 | for pattern, source in ((_GITHUB_URL_REPO_RE, url), (_GITHUB_TEXT_REPO_RE, text)): |
| 445 | for match in pattern.findall(source): |
| 446 | owner = match.split("/")[0].lower() |
| 447 | if owner in skip_owners: |
| 448 | continue |
| 449 | lower = match.lower() |
| 450 | if lower not in seen: |
| 451 | seen.add(lower) |
| 452 | repos.append(match) |
| 453 | return repos[:5] # cap at 5 repos |
| 454 | |
| 455 | |
| 456 | _INTEGRATION_SUFFIX_KEYWORDS: dict[str, set[str]] = { |
| 457 | "-action": {"action", "actions", "workflow", "workflows"}, |
| 458 | "-sdk": {"sdk", "client", "library"}, |
| 459 | "-plugin": {"plugin", "plugins", "extension", "extensions"}, |
| 460 | "-plugins": {"plugin", "plugins", "extension", "extensions"}, |
| 461 | "-docs": {"docs", "documentation"}, |
| 462 | "-examples": {"example", "examples", "sample", "samples"}, |
| 463 | "-template": {"template", "templates", "starter", "boilerplate"}, |
| 464 | } |
| 465 | |
| 466 | |
| 467 | def _topic_tokens(topic: str) -> set[str]: |
| 468 | return set(re.findall(r"[a-z0-9]+", (topic or "").lower())) |
| 469 | |
| 470 | |
| 471 | def _topic_entity_slugs(topic: str) -> list[str]: |
| 472 | entities = re.split(r"\b(?:vs|versus)\b", (topic or "").lower()) |
| 473 | slugs: list[str] = [] |
| 474 | for entity in entities: |
| 475 | tokens = re.findall(r"[a-z0-9]+", entity) |
| 476 | if tokens: |
| 477 | slugs.append("-".join(tokens)) |
| 478 | return slugs |
| 479 | |
| 480 | |
| 481 | def _repo_slug(repo: str) -> str: |
| 482 | parts = repo.split("/", 1) |
| 483 | if len(parts) != 2: |
| 484 | return "" |
| 485 | return parts[1].lower() |
| 486 | |
| 487 | |
| 488 | def _canonicalize_integration_repo(topic: str, repo: str) -> str: |
| 489 | """Map integration repos back to canonical product repos when intent allows. |
| 490 | |
| 491 | Example: |
| 492 | anthropics/claude-code-action -> anthropics/claude-code |
| 493 | unless topic explicitly asks for "action"/"workflow". |
| 494 | """ |
| 495 | parts = repo.split("/", 1) |
| 496 | if len(parts) != 2: |
| 497 | return repo |
| 498 | owner, name = parts[0], parts[1] |
| 499 | lower_name = name.lower() |
| 500 | topic_words = _topic_tokens(topic) |
| 501 | for suffix, intent_words in _INTEGRATION_SUFFIX_KEYWORDS.items(): |
| 502 | if not lower_name.endswith(suffix): |
| 503 | continue |
| 504 | if topic_words.intersection(intent_words): |
| 505 | return repo |
| 506 | base = name[: -len(suffix)] |
| 507 | if base: |
| 508 | return f"{owner}/{base}" |
| 509 | return repo |
| 510 | |
| 511 | |
| 512 | def canonicalize_github_repos(topic: str, repos: list[str], *, cap: int | None = 5) -> list[str]: |
| 513 | """Normalize/priority-sort GitHub repos for the current topic. |
| 514 | |
| 515 | - Rewrites common integration suffixes to canonical product repos when |
| 516 | topic intent does not mention those integrations. |
| 517 | - Promotes exact topic slug matches (e.g., `claude-code`) over partials. |
| 518 | """ |
| 519 | canonicalized: list[str] = [] |
| 520 | seen: set[str] = set() |
| 521 | for repo in repos: |
| 522 | candidate = _canonicalize_integration_repo(topic, repo.strip()) |
| 523 | if "/" not in candidate: |
| 524 | continue |
| 525 | key = candidate.lower() |
| 526 | if key in seen: |
| 527 | continue |
| 528 | seen.add(key) |
| 529 | canonicalized.append(candidate) |
| 530 | |
| 531 | topic_slugs = set(_topic_entity_slugs(topic)) |
| 532 | if topic_slugs: |
| 533 | exact = [r for r in canonicalized if _repo_slug(r) in topic_slugs] |
| 534 | prefixed = [r for r in canonicalized if any(_repo_slug(r).startswith(f"{slug}-") for slug in topic_slugs) and r not in exact] |
| 535 | rest = [r for r in canonicalized if r not in exact and r not in prefixed] |
| 536 | canonicalized = exact + prefixed + rest |
| 537 | |
| 538 | if cap is not None: |
| 539 | return canonicalized[:cap] |
| 540 | return canonicalized |
| 541 | |
| 542 | |
| 543 | def _build_context_summary(items: list[dict]) -> str: |
| 544 | """Build a 1-2 sentence current events summary from news search results.""" |
| 545 | snippets: list[str] = [] |
| 546 | for item in items[:3]: |
| 547 | snippet = item.get("snippet", "").strip() |
| 548 | if snippet: |
| 549 | snippets.append(snippet) |
| 550 | if not snippets: |
| 551 | return "" |
| 552 | # Take the first two meaningful snippets and truncate to keep it concise |
| 553 | combined = " ".join(snippets[:2]) |
| 554 | if len(combined) > 300: |
| 555 | combined = combined[:297] + "..." |
| 556 | return combined |
| 557 | |
| 558 | |
| 559 | def auto_resolve(topic: str, config: dict) -> dict: |
| 560 | """Discover subreddits, X handles, and current events context for a topic. |
| 561 | |
| 562 | Args: |
| 563 | topic: The research topic. |
| 564 | config: Dict with a Brave, Exa, Serper, or Parallel API key. |
| 565 | |
| 566 | Returns: |
| 567 | Dict with keys: subreddits, x_handle, github_user, github_repos, |
| 568 | context, category, searches_run. Returns empty result if no web |
| 569 | search backend is available. |
| 570 | """ |
| 571 | empty = { |
| 572 | "subreddits": [], |
| 573 | "x_handle": "", |
| 574 | "github_user": "", |
| 575 | "github_repos": [], |
| 576 | "trustpilot_domain": "", |
| 577 | "context": "", |
| 578 | "category": None, |
| 579 | "searches_run": 0, |
| 580 | } |
| 581 | |
| 582 | if not _has_backend(config): |
| 583 | _log("No web search backend available, skipping resolve") |
| 584 | return empty |
| 585 | |
| 586 | from_date, to_date = dates.get_date_range(30) |
| 587 | date_range = (from_date, to_date) |
| 588 | now = datetime.now(timezone.utc) |
| 589 | current_month = now.strftime("%B") |
| 590 | current_year = now.strftime("%Y") |
| 591 | |
| 592 | queries = { |
| 593 | "subreddit": f"{topic} subreddit reddit", |
| 594 | "news": f"{topic} news {current_month} {current_year}", |
| 595 | "x_handle": f"{topic} X twitter handle", |
| 596 | "github": f"{topic} github profile site:github.com", |
| 597 | } |
| 598 | |
| 599 | results: dict[str, list[dict]] = {} |
| 600 | searches_run = 0 |
| 601 | |
| 602 | def _search(label: str, query: str) -> tuple[str, list[dict]]: |
| 603 | items, _artifact = grounding.web_search(query, date_range, config) |
| 604 | return label, items |
| 605 | |
| 606 | with ThreadPoolExecutor(max_workers=3) as executor: |
| 607 | futures = { |
| 608 | executor.submit(_search, label, q): label |
| 609 | for label, q in queries.items() |
| 610 | } |
| 611 | for future in as_completed(futures): |
| 612 | label = futures[future] |
| 613 | try: |
| 614 | _label, items = future.result() |
| 615 | results[label] = items |
| 616 | searches_run += 1 |
| 617 | except Exception as exc: |
| 618 | _log(f"Search failed for {label}: {exc}") |
| 619 | results[label] = [] |
| 620 | |
| 621 | subreddits = _extract_subreddits(results.get("subreddit", [])) |
| 622 | x_handle = _extract_x_handle(results.get("x_handle", [])) |
| 623 | github_user = _extract_github_user(results.get("github", [])) |
| 624 | github_repos = canonicalize_github_repos(topic, _extract_github_repos(results.get("github", []))) |
| 625 | context = _build_context_summary(results.get("news", [])) |
| 626 | # Official-site domain doubles as the Trustpilot targeting hint (review |
| 627 | # pages are keyed by domain). Scan news first (official sites surface in |
| 628 | # coverage), then the handle query's profile-adjacent results. |
| 629 | trustpilot_domain = _extract_official_domain( |
| 630 | topic, (results.get("news") or []) + (results.get("x_handle") or []) |
| 631 | ) |
| 632 | |
| 633 | subreddits, category = _merge_category_peers(topic, subreddits) |
| 634 | |
| 635 | _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}") |
| 636 | |
| 637 | return { |
| 638 | "subreddits": subreddits, |
| 639 | "x_handle": x_handle, |
| 640 | "github_user": github_user, |
| 641 | "github_repos": github_repos, |
| 642 | "trustpilot_domain": trustpilot_domain, |
| 643 | "context": context, |
| 644 | "category": category, |
| 645 | "searches_run": searches_run, |
| 646 | } |
| 647 |