AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(engine): search installed lanes on host plans and require an X handle decision (#1323)
Matt Van Horn6bcc127aff67
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex ea82ec94..bc8a6c11 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -494,6 +494,12 @@ Runs that may skip the plan stay unaffected: `--mock`, `--hiring-signals`, `--auOutside a detected agent host nothing changes. The engine still plans internally and prints the LAW 7 reminder whenever it ends on the deterministic fallback, including when the internal planner fails (for example an HTTP 402 from a provider with no credits).+### What the engine adds to and checks on a host plan++A `--plan`'s per-subquery `sources` stay final, with one exception: an installed or opted-in source (digg, arxiv, techmeme, bluesky, truthsocial, stocktwits, linkedin, dripstack, devto, telegram, trustpilot) that is available but named in no subquery is added to the first subquery, and the engine logs a `[Planner]` line naming it. Host planners used to leave these out, so an installed `digg-pp-cli` was never searched on hosted runs. To keep one out deliberately, set `EXCLUDE_SOURCES` or restrict the run with `--search`.++On an agent-hosted run whose plan searches `x` for an entity-shaped topic (a short name such as `Jev` or `Peter Steinberger`, not a question or a theme), the engine exits 2 unless the command carries `--x-handle` or `--no-x-handle="<reason>"`. `--official-site=<domain>` lets the engine read the handle from the site's homepage links, with no API key; a handle you pass with `--x-handle` wins over the homepage. Quick runs, comparison runs, topics that already contain an `@handle`, and runs whose plan does not search X are exempt.+### Provider endpoint overridesPoint a provider at a gateway (LiteLLM, an enterprise proxy, a self-hosted OpenAI-compatible server) without a code change:diff --git a/changelog.d/+host-plan-lanes-and-handles.fixed.md b/changelog.d/+host-plan-lanes-and-handles.fixed.mdnew file mode 100644index 00000000..d88e2617--- /dev/null+++ b/changelog.d/+host-plan-lanes-and-handles.fixed.md@@ -0,0 +1 @@+Hosted runs now search installed lanes such as Digg even when the host's plan leaves them out, and stop printing "0 clusters" for sources that were never searched. Entity runs resolve the subject's X handle more reliably: `--official-site` reads the handle from the brand's homepage links with no API key, the runbook restricts X searches with the search tool's domain filter, and a hosted entity run that plans X now exits 2 until it passes `--x-handle` or `--no-x-handle="<reason>"`.diff --git a/skills/last30days/references/research-runbook.md b/skills/last30days/references/research-runbook.mdindex 697ca5fb..85b88328 100644--- a/skills/last30days/references/research-runbook.md+++ b/skills/last30days/references/research-runbook.md@@ -158,6 +158,8 @@ Before running the engine, determine every applicable targeting flag and resolve| Flag | Resolved in | Applies when ||------|-------------|--------------|| `--x-handle={handle}` | Step 0.5 (Section A below) | X is in `ACTIVE_SOURCES_LIST` and the topic is a person, brand, product, or creator with an X presence |+| `--official-site={domain}` | Step 0.5 (Section A below) | Company / product / service with a website; the engine fills unset `--x-handle` / `--github-user` from its homepage links |+| `--no-x-handle="{reason}"` | Step 0.5 (Section A below) | X is active, the topic is entity-shaped, and no first-party X account was found || `--x-related={h1,h2,...}` | Step 0.5 (Section A below) | X is in `ACTIVE_SOURCES_LIST` and the 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 |@@ -181,63 +183,47 @@ Before running the engine, determine every applicable targeting flag and resolveIf `ACTIVE_SOURCES_LIST` contains `x` and TOPIC looks like it could have its own X/Twitter account - **people, creators, brands, products, tools, companies, communities** (e.g., "Dor Brothers", "Jason Calacanis", "Nano Banana Pro", "Seedance", "Midjourney"), do WebSearches to find handles in three categories. If X is not active, skip this section without prompting or trying to unlock it.+**Restrict X searches with the tool's domain filter, not `site:x.com` (often ignored).** Use the domain parameter (Claude Code WebSearch: `allowed_domains: ["x.com", "twitter.com"]`); without one, keep only x.com / twitter.com result URLs. No x.com URLs back means the search failed: rephrase and retry.++**The engine checks this step:** a hosted run whose plan searches `x` for an entity-shaped topic exits 2 without `--x-handle` or `--no-x-handle="{reason}"`. Use the latter only after both lookups below come up empty.+**1. Primary handle** (the entity itself):+- **Company, product, or service:** pass `--official-site={domain}` (e.g. `typesafe.ai`); the engine reads the `x.com/{handle}` and `github.com/{org}` links on the homepage, keyless. A homepage link beats a search snippet.+- **Otherwise, or when the site links no X account:**```-WebSearch("{TOPIC} X twitter handle site:x.com")+WebSearch("{TOPIC} on X", allowed_domains: ["x.com", "twitter.com"])```**2. Company/organization handle OR founder/creator handle** -- This mapping is bidirectional:- If the topic is a **PERSON**, resolve their company's X handle. A CEO's story is inseparable from their company's story.- If the topic is a **PRODUCT or COMPANY**, resolve the founder/creator's personal X handle. The creator's personal account often has the most candid, high-signal content.```-WebSearch("{TOPIC} company CEO of site:x.com")+WebSearch("{TOPIC} company CEO", allowed_domains: ["x.com", "twitter.com"])```OR for products:```-WebSearch("{TOPIC} creator founder X twitter site:x.com")+WebSearch("{FOUNDER_NAME} {TOPIC} founder", allowed_domains: ["x.com", "twitter.com"])```+Get the founder's name from news first. Handles often omit the name (TypeSafe's Diogo Almeida is @CompleteSkeptic), so take it from evidence: an `x.com/{handle}/status/...` result titled "{Name} on X", or a "{Name} (@handle)" mention.Examples: Sam Altman -> @OpenAI, Dario Amodei -> @AnthropicAI, OpenClaw -> @steipete (Peter Steinberger), Paperclip -> @dotta, Claude Code -> @alexalbert__.**3. 1-2 related handles** -- People/entities closely associated with the topic (spouse, collaborator, band member), PLUS 1-2 prominent commentator/media handles that regularly cover this topic:```-WebSearch("{RELATED_PERSON_OR_ENTITY} X twitter handle site:x.com")+WebSearch("{RELATED_PERSON_OR_ENTITY} on X", allowed_domains: ["x.com", "twitter.com"])```-For a music artist, find music commentary accounts (e.g., @PopBase, @HotFreestyle, @DailyRapFacts).-For a tech CEO, find tech media accounts (e.g., @TechCrunch, @TheInformation).-For a product, find reviewer accounts in that category.--From the results, extract their X/Twitter handles. Look for:-- **Verified profile URLs** like `x.com/{handle}` or `twitter.com/{handle}`-- Mentions like "@handle" in bios, articles, or social profiles-- "Follow @handle on X" patterns--**Verify accounts are real, not parody/fan accounts.** Check for:-- Verified/blue checkmark in the search results-- Official website linking to the X account-- Consistent naming (e.g., @thedorbrothers for "The Dor Brothers", not @DorBrosFan)-- If results only show fan/parody/news accounts (not the entity's own account), skip - the entity may not have an X presence+Commentators: music accounts (@PopBase) for an artist, tech media (@TechCrunch) for a CEO, category reviewers for a product.-Pass handles to the CLI:-- Primary: `--x-handle={handle}` (without @)-- Related: `--x-related={handle1},{handle2},{company_handle},{commentator_handles}` (comma-separated, without @)+Take handles from `x.com/{handle}` profile URLs, "{Name} (@handle)" mentions, and "Follow @handle" lines. Skip fan, parody, and news accounts: prefer a verified account, one the official site links, and consistent naming (@thedorbrothers, not @DorBrosFan).-Example for "Kanye West":-- Primary: `--x-handle=kanyewest`-- Related: `--x-related=travisscott,PopBase,HotFreestyle`+Pass handles without @: `--x-handle={handle}` and `--x-related={h1},{h2},{company},{commentators}`. Examples: Kanye West is `--x-handle=kanyewest --x-related=travisscott,PopBase,HotFreestyle`; Sam Altman is `--x-handle=sama --x-related=OpenAI,TechCrunch`. Related handles get weight 0.3 so they do not crowd out the primary entity.-Example for "Sam Altman":-- Primary: `--x-handle=sama`-- Related: `--x-related=OpenAI,TechCrunch`--Related handles are searched with lower weight (0.3) so they appear in results but don't dominate over the primary entity's content.--**Note about @grok:** Grok is Elon's AI on X (xAI). It often appears in search results with thoughtful, accurate analysis. When citing @grok in your synthesis, frame it as "per Grok's AI analysis of [article/topic]" rather than treating it as an independent human commentator.+**Note about @grok:** @grok is xAI's AI on X. Cite it as "per Grok's AI analysis of [topic]", never as an independent human commentator.**Skip this step if:**- TOPIC is clearly a generic concept, not an entity (e.g., "best rap songs 2026", "how to use Docker", "AI ethics debate")- TOPIC already contains @ (user provided the handle directly)- Using `--quick` depth-- WebSearch shows no official X account exists for this entity+- Neither the official site nor an X-restricted search found a first-party account (pass `--no-x-handle="{reason}"`)Store: `RESOLVED_HANDLE = {handle or empty}`, `RESOLVED_RELATED = {comma-separated handles or empty}`@@ -245,24 +231,11 @@ Store: `RESOLVED_HANDLE = {handle or empty}`, `RESOLVED_RELATED = {comma-separat**MANDATORY when the topic is a person (developer, creator, CEO, founder, engineer, researcher) and WebSearch is available.** Resolve GitHub independently of the X handle. Without `--github-user={handle}`, GitHub search becomes a keyword match across all of GitHub instead of person-mode scoped to `user:{handle}`. The result is typically 5-10 thin unrelated items instead of the person's actual commits, PRs, releases, and top-starred repos. Treat this as a peer step to Step 0.5 (X handle resolution), not an afterthought.-Do the WebSearch:-```-WebSearch("{TOPIC} github profile site:github.com")+WebSearch("{TOPIC} github profile", allowed_domains: ["github.com"])```-From the results, extract their GitHub username from URLs like `github.com/{username}`.--**Verify the account is correct:** Check that the profile description or pinned repos match the person you're researching. Common names may return multiple profiles.--Pass to the CLI: `--github-user={username}` (without @)--Worked examples:-- For "Peter Steinberger", a WebSearch for `Peter Steinberger github profile site:github.com` returns @steipete. Pass `--github-user=steipete`.-- For "Matt Van Horn": `--github-user=mvanhorn`-- For "Garry Tan": `--github-user=garrytan`--**Person-mode GitHub tells a different story than keyword search.** Instead of "who mentioned this person in an issue body," it answers: "What are they shipping? Where are they getting merged? What do their own projects look like?" The engine fetches PR velocity, top repos with star counts, release notes, and README summaries.+Take the username from a `github.com/{username}` URL whose bio or pinned repos match the person (common names return several profiles), and pass `--github-user={username}` without @. Examples: Peter Steinberger is `steipete`, Matt Van Horn is `mvanhorn`, Garry Tan is `garrytan`. Person mode fetches what they ship: PR velocity, top repos, releases, and READMEs.**Skip this step if:**- TOPIC is clearly NOT a person (products, concepts, events)@@ -279,19 +252,10 @@ Store: `RESOLVED_GITHUB_USER = {username or empty}`If TOPIC looks like a product, tool, or open source project (not a person), resolve its GitHub repo for project-mode search:```-WebSearch("{TOPIC} github repo site:github.com")+WebSearch("{TOPIC} github repo", allowed_domains: ["github.com"])```-From the results, extract `owner/repo` from URLs like `github.com/{owner}/{repo}`.--Pass to the CLI: `--github-repo={owner/repo}`--For comparisons ("X vs Y"), resolve repos for both topics: `--github-repo={repo_a},{repo_b}`--Example for "OpenClaw": `--github-repo=openclaw/openclaw`-Example for "OpenClaw vs Paperclip": `--github-repo=openclaw/openclaw,paperclipai/paperclip`--Project-mode GitHub fetches live star counts, README snippets, latest releases, and top issues directly from the API. This is always more accurate than blog posts or YouTube videos citing weeks-old numbers.+Take `owner/repo` from `github.com/{owner}/{repo}` URLs and pass `--github-repo={owner/repo}`; for "X vs Y" pass both (`--github-repo=openclaw/openclaw,paperclipai/paperclip`). Project mode fetches live stars, READMEs, releases, and top issues.**Skip this step if:**- TOPIC is a person (use `--github-user` instead)@@ -546,7 +510,7 @@ Only show lines for platforms where something was resolved. Skip empty lines. On**Rules for your plan:**- Emit 1 to 4 subqueries (more for complex/multi-faceted topics, fewer for simple ones)-- **CRITICAL: Your PRIMARY subquery MUST include every applicable source from `ACTIVE_SOURCES_LIST` among reddit, x, youtube, tiktok, instagram, hackernews, polymarket.** Never invent an unavailable source. Preserve X whenever it is active; when it is unavailable, continue with the rest. Never omit active Reddit (highest-signal discussion) or active YouTube (unique transcripts + official content). Secondary subqueries can target specific platforms. Per-subquery `sources` on `--plan` is a contract at every depth (quick, default, and deep): the engine searches only those sources and does not expand a narrow list to every available source. Restrict a subquery only when you mean it.+- **CRITICAL: Your PRIMARY subquery MUST include every applicable source from `ACTIVE_SOURCES_LIST`, including installed lanes such as digg, arxiv, techmeme, bluesky, and linkedin.** Leave out only `grounding`, `corpus`, `perplexity`, `jobs` (engine-attached) and `amazon` / `meta_ads` (Step 0.5e / 0.5f). Never invent an unavailable source. Preserve X whenever it is active; when it is unavailable, continue with the rest. Never omit active Reddit (highest-signal discussion) or active YouTube (unique transcripts + official content). Secondary subqueries can target specific platforms. Per-subquery `sources` on `--plan` is a contract at every depth (quick, default, and deep): the engine searches only those sources and does not expand a narrow list to every available source. Restrict a subquery only when you mean it.- `search_query` should be concise and keyword-heavy - match how content is TITLED on platforms- `ranking_query` should read like a natural language question- **X disambiguation:** express your disambiguation intent in `ranking_query` (e.g., "What are people saying about Rome the city in Italy, not AS Roma or Rome Odunze?") — do not phrase-quote `search_query` for X or invent X operators; the engine handles X query compilation internally.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 11fc8c4d..e8e9535c 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -799,6 +799,24 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--store", action="store_true", help="Persist ranked findings to the SQLite research store")parser.add_argument("--x-handle", help="X handle for targeted supplemental search")parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)")+ parser.add_argument(+ "--official-site",+ metavar="DOMAIN",+ help=(+ "The topic's own website (e.g., typesafe.ai). The engine reads the X and "+ "GitHub accounts the homepage links and uses them when --x-handle / "+ "--github-user are not set. Keyless."+ ),+ )+ parser.add_argument(+ "--no-x-handle",+ metavar="REASON",+ help=(+ "Record that the topic has no resolvable X account, and why (e.g., "+ "\"official site links no X account; x.com-filtered search found none\"). "+ "Satisfies the agent-hosted X handle decision check without --x-handle."+ ),+ )parser.add_argument("--x-posts",dest="x_posts",@@ -1254,7 +1272,14 @@ def _show_runtime_ui(display_sources = list(dict.fromkeys([- *report.query_plan.source_weights.keys(),+ # Subquery sources, not source_weights: the sanitizer weights+ # every eligible source, so weights alone would print+ # "Digg: 0 clusters" for a source that was never searched.+ *(+ source+ for subquery in report.query_plan.subqueries+ for source in subquery.sources+ ),*report.items_by_source.keys(),*report.errors_by_source.keys(),]@@ -2751,6 +2776,50 @@ def _comparison_requested(args: argparse.Namespace, topic: str) -> bool:LAW7_HOST_PLAN_EXIT = 2+X_HANDLE_DECISION_EXIT = 2+++def _x_handle_decision_signal(+ args: argparse.Namespace, topic: str, external_plan: object,+ available_sources: list[str],+) -> str:+ """Agent-host marker when a hosted entity run plans X with no handle decision.++ An entity topic's own posts are the primary X evidence, and only a+ resolved handle lets X search them. On hosted runs the host model resolves+ handles (the engine's auto-resolve stands down for --plan), so a skipped+ lookup used to cost nothing and went unnoticed. Returns "" when the run+ is exempt or already decided (--x-handle or --no-x-handle), or when X+ will not run (unavailable, --search without x, or EXCLUDE_SOURCES=x).+ """+ if external_plan is None or args.mock or args.quick:+ return ""+ if args.x_handle or args.no_x_handle:+ return ""+ if "@" in topic or _comparison_requested(args, topic):+ return ""+ if not _looks_like_entity_topic(topic):+ return ""+ if "x" not in available_sources:+ return ""+ if not pipeline._external_plan_names_source(external_plan, "x"):+ return ""+ return env.agent_host_signal()+++def _x_handle_decision_message(signal: str) -> str:+ return (+ "[Resolve] X handle decision missing: this run is agent-hosted "+ f"({signal} is set), the topic names a person, company, or product, and "+ "the plan searches X, but the command has no --x-handle. Without one X "+ "cannot search the subject's own posts. Resolve it first "+ "(references/research-runbook.md Step 0.5, Section A): pass "+ "--official-site=<domain> so the engine reads the handle from the "+ "homepage links, or find it with a search restricted to x.com through "+ "your search tool's domain filter, then re-run with --x-handle=<handle>. "+ "If both came up empty, or the topic is a theme rather than an entity, "+ "re-run with --no-x-handle=\"<reason>\".\n"+ )def _law7_host_plan_message(signal: str) -> str:@@ -3919,6 +3988,9 @@ def _main(# without WebSearch (OpenClaw, Codex, raw CLI).repos_from_auto_resolve = Falsetrustpilot_domain_is_hint = False+ x_handle_from_auto = False+ github_user_from_auto = False+ auto_official_site = ""# Resolve automatically for entity-shaped topics even without the flag.# A person or company topic whose handle the user did not supply is the# case where first-party evidence is hardest to protect: the handle is@@ -3955,11 +4027,13 @@ def _main(sys.stderr.write(f"[AutoResolve] Subreddits: {', '.join(subreddits)}\n")if resolution.get("x_handle") and not args.x_handle:args.x_handle = resolution["x_handle"]+ x_handle_from_auto = Truesys.stderr.write(f"[AutoResolve] X handle: @{args.x_handle}\n")# Empty x_handle is intentional: do not invent a lexical stand-in.# pipeline.run treats an unidentified subject as "skip the X floor".if resolution.get("github_user") and not args.github_user:args.github_user = resolution["github_user"]+ github_user_from_auto = Truesys.stderr.write(f"[AutoResolve] GitHub user: @{args.github_user}\n")if resolution.get("github_repos") and not args.github_repo:args.github_repo = ",".join(resolution["github_repos"])@@ -3973,6 +4047,9 @@ def _main(args.trustpilot_domain = resolution["trustpilot_domain"]trustpilot_domain_is_hint = Truesys.stderr.write(f"[AutoResolve] Trustpilot domain: {args.trustpilot_domain} (hint)\n")+ if resolution.get("trustpilot_domain"):+ # The brand's review-page domain is its own site.+ auto_official_site = resolution["trustpilot_domain"]if resolution.get("context"):# Inject context into external_plan metadata for the planner to useif not external_plan:@@ -3981,6 +4058,29 @@ def _main(config["_auto_resolve_context"] = resolution["context"]sys.stderr.write(f"[AutoResolve] Context: {resolution['context'][:80]}...\n")+ # The brand's homepage links its own X and GitHub accounts: the most+ # reliable first-party source, and keyless. A user flag wins over the+ # homepage; the homepage wins over a handle auto-resolve picked by+ # counting mentions in search results.+ official_site = (args.official_site or "").strip() or auto_official_site+ if official_site and not args.mock:+ from lib import resolve as resolve_lib+ socials = resolve_lib.official_site_socials(official_site)+ if socials["x_handle"] and (not args.x_handle or x_handle_from_auto):+ args.x_handle = socials["x_handle"]+ sys.stderr.write(f"[Resolve] X handle from {official_site}: @{args.x_handle}\n")+ if socials["github_user"] and (not args.github_user or github_user_from_auto):+ args.github_user = socials["github_user"]+ sys.stderr.write(f"[Resolve] GitHub user from {official_site}: @{args.github_user}\n")+ if args.no_x_handle and not args.x_handle:+ sys.stderr.write(f"[Resolve] No X handle: {args.no_x_handle.strip()}\n")+ x_decision_signal = _x_handle_decision_signal(+ args, topic, external_plan, diag.get("available_sources") or [],+ )+ if x_decision_signal:+ sys.stderr.write(_x_handle_decision_message(x_decision_signal))+ raise SystemExit(X_HANDLE_DECISION_EXIT)+github_user = args.github_user.lstrip("@").lower() if args.github_user else Nonegithub_repos = [r.strip() for r in args.github_repo.split(",") if r.strip() and "/" in r.strip()] if args.github_repo else Nonetrustpilot_domain = args.trustpilot_domain.strip() if args.trustpilot_domain else Nonediff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex abb3dcb1..08d763d2 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -2383,6 +2383,9 @@ def run(external_plan, topic, available, planner_requested_sources, depth,honor_plan_sources=True,)+ # Quick runs keep the sanitizer's two-source budget.+ if depth != "quick":+ _ensure_unplanned_lanes_in_host_plan(plan, available)plan_source = "external"else:_check_research(config)@@ -3765,6 +3768,53 @@ def _ensure_devto_in_plan(plan: schema.QueryPlan, available: list[str]) -> None:plan.source_weights = planner._normalize_weights(plan.source_weights)+# Sources that are available only because the user installed their CLI or opted+# in (INCLUDE_SOURCES, --search, a targeting flag). A host plan that names none+# of them in any subquery almost always means the host planner never knew to+# list them, not that it chose to skip them, so they ride the primary subquery.+# Paid lanes with their own host decision step (amazon, meta_ads) stay out;+# EXCLUDE_SOURCES and --search already filter ``available``.+HOST_PLAN_BACKFILL_SOURCES = (+ "digg",+ "arxiv",+ "techmeme",+ "bluesky",+ "truthsocial",+ "stocktwits",+ "linkedin",+ "dripstack",+ "devto",+ "telegram",+ "trustpilot",+)+++def _ensure_unplanned_lanes_in_host_plan(+ plan: schema.QueryPlan,+ available: list[str],+) -> None:+ if not plan.subqueries:+ return+ planned = {source for subquery in plan.subqueries for source in subquery.sources}+ missing = [+ source for source in HOST_PLAN_BACKFILL_SOURCES+ if source in available and source not in planned+ ]+ if not missing:+ return+ plan.subqueries[0].sources.extend(missing)+ for source in missing:+ plan.source_weights.setdefault(source, 1.0)+ plan.source_weights = planner._normalize_weights(plan.source_weights)+ log.source_log(+ "Planner",+ "Added installed/opted-in sources absent from every --plan subquery to "+ f"{plan.subqueries[0].label}: {', '.join(missing)} "+ "(set EXCLUDE_SOURCES to skip them).",+ tty_only=False,+ )++def _external_plan_names_source(external_plan: Any, source: str) -> bool:if not isinstance(external_plan, dict):return Falsediff --git a/skills/last30days/scripts/lib/resolve.py b/skills/last30days/scripts/lib/resolve.pyindex c9ed3974..12388a7d 100644--- a/skills/last30days/scripts/lib/resolve.py+++ b/skills/last30days/scripts/lib/resolve.py@@ -12,7 +12,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetime, timezonefrom typing import Optional-from . import categories, dates, grounding, log+from . import categories, dates, grounding, http, logMAX_SUBS = 10@@ -180,6 +180,126 @@ def _extract_official_domain(topic: str, items: list[dict]) -> str:return ""+_HREF = re.compile(r"""href\s*=\s*["']([^"']+)["']""", re.IGNORECASE)+# Profile links only: x.com/{handle} with nothing after the handle but a slash,+# query or fragment. /status/, /intent/ and /share links name someone else's+# post or a share widget, never the site's own account.+_X_PROFILE_LINK = re.compile(+ r"^(?:https?:)?//(?:www\.|mobile\.)?(?:x|twitter)\.com/([A-Za-z0-9_]{1,15})/?(?:[?#].*)?$",+ re.IGNORECASE,+)+_GITHUB_OWNER_LINK = re.compile(+ r"^(?:https?:)?//(?:www\.)?github\.com/([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))(?:[/?#].*)?$",+ re.IGNORECASE,+)+_X_NON_ACCOUNTS = {+ "twitter", "x", "search", "hashtag", "intent", "share", "i", "home",+ "explore", "settings", "login", "signup", "tos", "privacy", "messages",+ "notifications", "compose",+}+_GITHUB_NON_OWNERS = {+ "topics", "explore", "settings", "orgs", "search", "features", "about",+ "pricing", "enterprise", "login", "join", "sponsors", "marketplace",+ "apps", "collections", "trending", "site", "security", "customer-stories",+}+++def _official_site_url(site: str) -> str:+ """Normalize a domain or URL to the site's homepage URL, or ""."""+ text = (site or "").strip()+ if not text:+ return ""+ host = re.sub(r"^[a-z][a-z0-9+.-]*://", "", text, flags=re.IGNORECASE)+ host = re.split(r"[/?#]", host, maxsplit=1)[0].strip().lower()+ if not re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?", host):+ return ""+ return f"https://{host}/"+++_CHROME_REGION = re.compile(+ r"<(header|footer|nav)\b[^>]*>(.*?)</\1\s*>", re.IGNORECASE | re.DOTALL,+)+++def _site_label(url: str) -> str:+ """The registrable label of a homepage URL: https://www.typesafe.ai/ -> typesafe."""+ labels = url.split("://", 1)[-1].strip("/").split(":")[0].split(".")+ labels = [label for label in labels if label not in {"www", "m"}]+ return re.sub(r"[^a-z0-9]", "", labels[0].lower()) if labels else ""+++def _own_account(links: list[tuple[str, bool]], site_label: str) -> str:+ """The site's own account among its profile links, or "" when ambiguous.++ A homepage also links customers, testimonials, and dependencies, so+ link counts and page order cannot tell the site's account from someone+ else's. Accept an account only when it is the sole one linked, the sole+ one in the page's header/footer/nav, or the sole one named after the site.+ """+ # X and GitHub names are case-insensitive: TypeSafeAI and typesafeai are+ # one account. Keep the first spelling the page uses.+ spelling: dict[str, str] = {}+ for name, _ in links:+ spelling.setdefault(name.lower(), name)+ distinct = list(spelling.values())+ if len(distinct) <= 1:+ return distinct[0] if distinct else ""+ chrome = list(dict.fromkeys(spelling[name.lower()] for name, in_chrome in links if in_chrome))+ if len(chrome) == 1:+ return chrome[0]+ named = [+ name for name in (chrome or distinct)+ if site_label and len(site_label) >= 3+ and site_label in re.sub(r"[^a-z0-9]", "", name.lower())+ ]+ return named[0] if len(named) == 1 else ""+++def official_site_socials(site: str, *, timeout: int = 10) -> dict[str, str]:+ """Read a brand's own X and GitHub accounts from its homepage links.++ A company's homepage links its own accounts (usually in the header or+ footer), so this is the most reliable first-party source for the handle,+ and it needs no search key. Only ``href`` targets count: a handle quoted+ in page copy may be anyone's. Returns ``{"x_handle": ..., "github_user":+ ...}`` with "" for any account the page does not link, and both empty+ when the page cannot be fetched.+ """+ result = {"x_handle": "", "github_user": ""}+ url = _official_site_url(site)+ if not url:+ return result+ html = http.get_text(url, timeout=timeout, retries=1, accept="text/html")+ if not html:+ _log(f"Official site {url} could not be fetched")+ return result+ chrome_hrefs = {+ href.strip()+ for match in _CHROME_REGION.finditer(html)+ for href in _HREF.findall(match.group(2))+ }+ x_links: list[tuple[str, bool]] = []+ github_links: list[tuple[str, bool]] = []+ for href in _HREF.findall(html):+ href = href.strip()+ in_chrome = href in chrome_hrefs+ x_match = _X_PROFILE_LINK.match(href)+ if x_match and x_match.group(1).lower() not in _X_NON_ACCOUNTS:+ x_links.append((x_match.group(1), in_chrome))+ continue+ gh_match = _GITHUB_OWNER_LINK.match(href)+ if gh_match and gh_match.group(1).lower() not in _GITHUB_NON_OWNERS:+ github_links.append((gh_match.group(1), in_chrome))+ label = _site_label(url)+ result["x_handle"] = _own_account(x_links, label)+ result["github_user"] = _own_account(github_links, label)+ _log(+ f"Official site {url}: x_handle={result['x_handle']!r}, "+ f"github_user={result['github_user']!r}"+ )+ return result++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_.-]+)")diff --git a/tests/test_external_plan_source_contract.py b/tests/test_external_plan_source_contract.pyindex ca618407..883a8211 100644--- a/tests/test_external_plan_source_contract.py+++ b/tests/test_external_plan_source_contract.py@@ -55,11 +55,19 @@ def test_internal_empty_intersection_retains_fallback():assert plan.subqueries[0].sources == ["reddit", "hackernews"]-def _run_with_plan(topic, plan, **kwargs):+def _planned(report):+ """Subquery sources minus the installed/opted-in lanes the engine backfills."""+ return [+ [s for s in sq.sources if s not in pipeline.HOST_PLAN_BACKFILL_SOURCES]+ for sq in report.query_plan.subqueries+ ]+++def _run_with_plan(topic, plan, depth="default", **kwargs):with patch.object(pipeline, "_retrieve_stream", return_value=([], {})) as retrieve:report = pipeline.run(topic=topic, config={}, mock=True, web_backend="none",- depth="default", external_plan=plan, **kwargs,+ depth=depth, external_plan=plan, **kwargs,)return report, {call.kwargs["source"] for call in retrieve.call_args_list}@@ -68,9 +76,7 @@ def test_host_plan_on_company_topic_does_not_gain_jobs():report, fetched = _run_with_plan("Listen Labs", plan_with(["reddit", "youtube"], ["hackernews"]),)- assert [sq.sources for sq in report.query_plan.subqueries] == [- ["reddit", "youtube"], ["hackernews"],- ]+ assert _planned(report) == [["reddit", "youtube"], ["hackernews"]]assert "jobs" not in fetchedassert "jobs" not in report.source_status@@ -79,9 +85,7 @@ def test_host_plan_naming_jobs_keeps_it_on_non_company_topic():report, fetched = _run_with_plan("test topic", plan_with(["reddit", "jobs"], ["hackernews"]),)- assert [sq.sources for sq in report.query_plan.subqueries] == [- ["reddit", "jobs"], ["hackernews"],- ]+ assert _planned(report) == [["reddit", "jobs"], ["hackernews"]]assert "jobs" in fetched@@ -93,9 +97,7 @@ def test_host_plan_naming_jobs_does_not_override_excluded_jobs():external_plan=plan_with(["reddit", "jobs"], ["hackernews"]),)fetched = {call.kwargs["source"] for call in retrieve.call_args_list}- assert [sq.sources for sq in report.query_plan.subqueries] == [- ["reddit"], ["hackernews"],- ]+ assert _planned(report) == [["reddit"], ["hackernews"]]assert "jobs" not in fetched@@ -116,3 +118,60 @@ def test_hiring_mode_does_not_duplicate_jobs_already_in_host_plan():)assert len(report.query_plan.subqueries) == 2assert all(sq.sources.count("jobs") == 1 for sq in report.query_plan.subqueries)+++def test_host_plan_gains_installed_lanes_it_never_named(capsys):+ report, fetched = _run_with_plan(+ "test topic", plan_with(["reddit", "youtube"], ["hackernews"]),+ requested_sources=["reddit", "youtube", "hackernews", "digg", "arxiv"],+ )+ assert [sq.sources for sq in report.query_plan.subqueries] == [+ ["reddit", "youtube", "digg", "arxiv"], ["hackernews"],+ ]+ assert {"digg", "arxiv"} <= fetched+ assert "digg, arxiv" in capsys.readouterr().err+++def test_host_plan_lane_named_in_secondary_subquery_is_not_duplicated():+ report, _ = _run_with_plan(+ "test topic", plan_with(["reddit"], ["digg"]),+ requested_sources=["reddit", "digg"],+ )+ assert [sq.sources for sq in report.query_plan.subqueries] == [["reddit"], ["digg"]]+++def test_host_plan_backfill_only_adds_available_lanes():+ # EXCLUDE_SOURCES and --search filter ``available`` before the backfill runs.+ plan = planner._sanitize_plan(+ plan_with(["reddit"]), "test topic", ["reddit"], None, "default",+ honor_plan_sources=True,+ )+ pipeline._ensure_unplanned_lanes_in_host_plan(plan, ["reddit"])+ assert plan.subqueries[0].sources == ["reddit"]+++def test_host_plan_backfill_skips_paid_decision_lanes():+ plan = planner._sanitize_plan(+ plan_with(["reddit"]), "test topic", ["reddit", "amazon", "meta_ads"], None, "default",+ honor_plan_sources=True,+ )+ pipeline._ensure_unplanned_lanes_in_host_plan(plan, ["reddit", "amazon", "meta_ads"])+ assert plan.subqueries[0].sources == ["reddit"]+++def test_exclude_sources_keeps_an_installed_lane_out_of_the_backfill():+ def which(name):+ return "/fake/bin/digg-pp-cli" if name == "digg-pp-cli" else None++ with patch.object(pipeline, "which", side_effect=which):+ assert "digg" in pipeline.available_sources({})+ assert "digg" not in pipeline.available_sources({"EXCLUDE_SOURCES": "digg"})+++def test_quick_host_plan_keeps_its_source_budget():+ report, fetched = _run_with_plan(+ "test topic", plan_with(["reddit", "youtube"]),+ requested_sources=["reddit", "youtube", "digg", "arxiv"], depth="quick",+ )+ assert [sq.sources for sq in report.query_plan.subqueries] == [["reddit", "youtube"]]+ assert not {"digg", "arxiv"} & fetcheddiff --git a/tests/test_x_handle_resolution.py b/tests/test_x_handle_resolution.pynew file mode 100644index 00000000..78c9d340--- /dev/null+++ b/tests/test_x_handle_resolution.py@@ -0,0 +1,243 @@+"""Entity X handles: homepage links, and the hosted-run handle decision check.++Hosted runs pass --plan, so the engine's search-based auto-resolve stands down+and the host model resolves handles. A skipped lookup used to cost nothing:+the run went ahead with no --x-handle and X never searched the subject's own+posts. These tests pin the keyless homepage reader and the check that makes a+hosted entity run either name a handle or say why there is none.+"""++from __future__ import annotations++import io+import sys+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import pytest++import last30days as cli+from lib import resolve++DUMMY_CONFIG = {"OPENROUTER_API_KEY": "dummy-openrouter-key-000"}+DIAG = {+ "available_sources": ["reddit", "x", "hackernews"],+ "providers": {"google": False, "openai": False, "xai": False},+ "x_backend": None,+ "bird_installed": False,+ "bird_authenticated": False,+ "bird_username": None,+ "native_web_backend": None,+ "permission_preflight": {},+}+PLAN_WITH_X = (+ '{"intent":"product","freshness_mode":"balanced_recent","cluster_mode":"none",'+ '"subqueries":[{"label":"primary","search_query":"Jev","ranking_query":'+ '"What are people saying about Jev?","sources":["reddit","x","hackernews"],"weight":1.0}]}'+)+PLAN_WITHOUT_X = PLAN_WITH_X.replace('"x",', "")++HOMEPAGE = """+<html><body>+<a href="https://x.com/intent/tweet?text=hi">Share</a>+<a href="https://twitter.com/someone/status/123">Quoted post</a>+<p>Follow @notourhandle for updates</p>+<footer>+ <a href="https://x.com/typesafeai">X</a>+ <a href='https://twitter.com/typesafeai/'>Twitter</a>+ <a href="https://github.com/typesafe-ai/typesafe-sdk-python">SDK</a>+ <a href="https://github.com/typesafe-ai">GitHub</a>+ <a href="https://github.com/features">Features</a>+</footer>+</body></html>+"""+++class _RetrievalReached(Exception):+ pass+++def _run_main(monkeypatch, argv, *, host_env=None, socials=None, diag=None):+ for name in ("LAST30DAYS_API_KEY", "LAST30DAYS_API_BASE", "LAST30DAYS_MEMORY_DIR"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")+ for name, value in (host_env or {}).items():+ monkeypatch.setenv(name, value)+ monkeypatch.setattr(sys, "argv", ["last30days.py", *argv])+ run_mock = mock.Mock(side_effect=_RetrievalReached)+ socials_mock = mock.Mock(return_value=socials or {"x_handle": "", "github_user": ""})+ err = io.StringIO()+ with mock.patch.object(cli.env, "get_config", return_value=dict(DUMMY_CONFIG)), \+ mock.patch.object(cli.pipeline, "diagnose", mock.Mock(return_value=dict(diag or DIAG))), \+ mock.patch.object(cli.pipeline, "run", run_mock), \+ mock.patch("lib.resolve.auto_resolve", mock.Mock(return_value={})), \+ mock.patch("lib.resolve.official_site_socials", socials_mock), \+ mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock()), \+ redirect_stdout(io.StringIO()), redirect_stderr(err):+ try:+ rc = cli.main()+ except _RetrievalReached:+ rc = None+ except SystemExit as exc:+ rc = exc.code+ return rc, err.getvalue(), run_mock, socials_mock+++HOSTED = {"CLAUDECODE": "1"}+++# --- homepage reader -------------------------------------------------------+++def test_official_site_socials_reads_profile_links_only():+ with mock.patch.object(resolve.http, "get_text", return_value=HOMEPAGE) as get:+ socials = resolve.official_site_socials("typesafe.ai")+ assert socials == {"x_handle": "typesafeai", "github_user": "typesafe-ai"}+ assert get.call_args.args[0] == "https://typesafe.ai/"+++def test_official_site_socials_leaves_ambiguous_accounts_unresolved():+ page = """+ <a href="https://x.com/happycustomer">Customer</a>+ <a href="https://x.com/someinvestor">Investor</a>+ <a href="https://github.com/somedependency/lib">Built on</a>+ <a href="https://github.com/otherdependency">Also</a>+ """+ with mock.patch.object(resolve.http, "get_text", return_value=page):+ assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""}+++def test_official_site_socials_prefers_the_footer_over_a_repeated_testimonial():+ page = """+ <a href="https://x.com/happycustomer">quote</a>+ <a href="https://x.com/happycustomer">quote again</a>+ <footer><a href="https://x.com/acmehq">X</a></footer>+ """+ with mock.patch.object(resolve.http, "get_text", return_value=page):+ assert resolve.official_site_socials("example.com")["x_handle"] == "acmehq"+++def test_official_site_socials_prefers_the_account_named_after_the_site():+ page = """+ <a href="https://x.com/happycustomer">quote</a>+ <a href="https://x.com/TypeSafeAI">Follow us</a>+ """+ with mock.patch.object(resolve.http, "get_text", return_value=page):+ assert resolve.official_site_socials("www.typesafe.ai")["x_handle"] == "TypeSafeAI"+++def test_official_site_socials_treats_capitalizations_as_one_account():+ page = """+ <a href="https://x.com/TypeSafeAI">X</a>+ <a href="https://twitter.com/typesafeai">Twitter</a>+ <a href="https://github.com/TypeSafe-AI">GitHub</a>+ <a href="https://github.com/typesafe-ai/sdk">SDK</a>+ """+ with mock.patch.object(resolve.http, "get_text", return_value=page):+ assert resolve.official_site_socials("example.com") == {+ "x_handle": "TypeSafeAI", "github_user": "TypeSafe-AI",+ }+++def test_official_site_socials_empty_when_page_unreachable():+ with mock.patch.object(resolve.http, "get_text", return_value=None):+ assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""}+++ "site,url",+ [+ ("typesafe.ai", "https://typesafe.ai/"),+ ("https://www.TypeSafe.ai/pricing?x=1", "https://www.typesafe.ai/"),+ ("not a domain", ""),+ ("", ""),+ ],+)+def test_official_site_url_normalizes_to_homepage(site, url):+ assert resolve._official_site_url(site) == url+++def test_official_site_socials_skips_invalid_site_without_fetching():+ with mock.patch.object(resolve.http, "get_text") as get:+ assert resolve.official_site_socials("javascript:alert(1)") == {"x_handle": "", "github_user": ""}+ get.assert_not_called()+++# --- hosted handle decision check -----------------------------------------+++def test_hosted_entity_run_planning_x_without_handle_stops(monkeypatch):+ rc, err, run_mock, _ = _run_main(monkeypatch, ["Jev", "--plan", PLAN_WITH_X], host_env=HOSTED)+ assert rc == cli.X_HANDLE_DECISION_EXIT+ assert "X handle decision missing" in err+ assert "--official-site" in err and "--no-x-handle" in err+ run_mock.assert_not_called()+++def test_official_site_handle_satisfies_the_check(monkeypatch):+ rc, err, run_mock, socials_mock = _run_main(+ monkeypatch, ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai"],+ host_env=HOSTED, socials={"x_handle": "typesafeai", "github_user": "typesafe-ai"},+ )+ assert rc is None+ assert "@typesafeai" in err+ socials_mock.assert_called_once_with("typesafe.ai")+ assert run_mock.call_args.kwargs["x_handle"] == "typesafeai"+++def test_user_x_handle_beats_the_homepage(monkeypatch):+ rc, _err, run_mock, _ = _run_main(+ monkeypatch,+ ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai", "--x-handle", "CompleteSkeptic"],+ host_env=HOSTED, socials={"x_handle": "typesafeai", "github_user": ""},+ )+ assert rc is None+ assert run_mock.call_args.kwargs["x_handle"] == "CompleteSkeptic"+++def test_official_site_without_x_link_still_needs_a_decision(monkeypatch):+ rc, err, _run, _ = _run_main(+ monkeypatch, ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai"],+ host_env=HOSTED,+ )+ assert rc == cli.X_HANDLE_DECISION_EXIT+ assert "X handle decision missing" in err+++def test_no_x_handle_reason_satisfies_the_check(monkeypatch):+ rc, err, _run, _ = _run_main(+ monkeypatch,+ ["Jev", "--plan", PLAN_WITH_X, "--no-x-handle", "official site links no X account"],+ host_env=HOSTED,+ )+ assert rc is None+ assert "No X handle: official site links no X account" in err+++ "argv",+ [+ ["Jev", "--plan", PLAN_WITHOUT_X],+ ["Jev", "--plan", PLAN_WITH_X, "--quick"],+ ["how do decision models work?", "--plan", PLAN_WITH_X],+ ["@typesafeai", "--plan", PLAN_WITH_X],+ ],+)+def test_check_exempts_runs_that_do_not_need_a_handle(monkeypatch, argv):+ rc, _err, _run, _ = _run_main(monkeypatch, argv, host_env=HOSTED)+ assert rc is None+++def test_check_does_not_apply_when_x_will_not_run(monkeypatch):+ # --search without x, EXCLUDE_SOURCES=x, or no X backend all drop x from+ # diagnose's available_sources; the plan naming x must not stop the run.+ no_x = dict(DIAG, available_sources=["reddit", "hackernews"])+ rc, _err, _run, _ = _run_main(+ monkeypatch, ["Jev", "--plan", PLAN_WITH_X], host_env=HOSTED, diag=no_x,+ )+ assert rc is None+++def test_check_does_not_apply_outside_agent_hosts(monkeypatch):+ rc, _err, _run, _ = _run_main(monkeypatch, ["Jev", "--plan", PLAN_WITH_X])+ assert rc is None