返回 last30days-skill
planner.py
根目录 / skills / last30days / scripts / lib / planner.py
1 """LLM-first query planning with deterministic guards for risky queries."""
2
3 from __future__ import annotations
4
5 import copy
6 import json
7 import math
8 import re
9 import unicodedata
10 from collections import Counter
11 from contextlib import nullcontext
12 from dataclasses import replace
13 from threading import Event
14
15 from . import (
16 categories, competitors, entity_extract, http, jobs_story, log, polymarket, providers, query, relevance,
17 schema,
18 )
19
20 # Hebrew Unicode block: U+0590–U+05FF
21 _HEBREW_RE = re.compile(r'[\u0590-\u05FF]')
22
23 DISCOVERY_SOURCE_ORDER = ("reddit", "hackernews", "digg", "x")
24
25 # Installed/opted-in lanes that can be backfilled into a host plan.
26 HOST_PLAN_BACKFILL_SOURCES = (
27 "digg",
28 "arxiv",
29 "techmeme",
30 "news_rss",
31 "bluesky",
32 "truthsocial",
33 "stocktwits",
34 "linkedin",
35 "dripstack",
36 "devto",
37 "v2ex",
38 "juejin",
39 "telegram",
40 "trustpilot",
41 )
42
43
44 def detect_language(text: str) -> str | None:
45 """Return 'he' if the text contains Hebrew characters, else None."""
46 return 'he' if _HEBREW_RE.search(text) else None
47
48
49 def build_discovery_plan(
50 domain: str,
51 *,
52 available_sources: list[str] | None = None,
53 subreddits: list[str] | None = None,
54 ) -> schema.DiscoveryPlan:
55 """Resolve a domain to the existing category-peer community feeds.
56
57 An empty domain is global trending: sweep every river feed's own hot list
58 (r/all, HN front page, Digg) with no category scoping. Keyword-driven
59 sources (X, Techmeme, arXiv - none of which expose a river/front-page
60 lane) sit out of the global nominate stage and join per-topic at the
61 enrichment pass, where every nomination gets a full research run.
62 """
63 normalized_domain = " ".join(domain.split())
64 if not normalized_domain:
65 resolved = [
66 subreddit.removeprefix("r/").strip()
67 for subreddit in (subreddits or ["all"])
68 if subreddit.strip()
69 ]
70 allowed = set(DISCOVERY_SOURCE_ORDER if available_sources is None else available_sources)
71 allowed.discard("x")
72 sources = [source for source in DISCOVERY_SOURCE_ORDER if source in allowed]
73 if not sources:
74 raise ValueError("No listing sources are available for global trending")
75 return schema.DiscoveryPlan(
76 domain="",
77 category=None,
78 subreddits=resolved or ["all"],
79 sources=sources,
80 )
81
82 category = categories.detect_category(normalized_domain)
83 candidate_subreddits = list(subreddits or categories.peer_subs_for(category))
84 seen_subreddits: set[str] = set()
85 resolved_subreddits: list[str] = []
86 for subreddit in candidate_subreddits:
87 normalized_subreddit = subreddit.removeprefix("r/").strip()
88 key = normalized_subreddit.lower()
89 if not normalized_subreddit or key in seen_subreddits:
90 continue
91 seen_subreddits.add(key)
92 resolved_subreddits.append(normalized_subreddit)
93 # The curated map intentionally stays small. Keep discovery's keyless floor
94 # for uncategorized domains by sweeping r/all and applying domain relevance
95 # during normalization instead of inventing a second category resolver.
96 if not resolved_subreddits:
97 resolved_subreddits = ["all"]
98
99 allowed = set(DISCOVERY_SOURCE_ORDER if available_sources is None else available_sources)
100 sources = [source for source in DISCOVERY_SOURCE_ORDER if source in allowed]
101 if not sources:
102 raise ValueError(f"No listing sources are available for {normalized_domain!r}")
103
104 return schema.DiscoveryPlan(
105 domain=normalized_domain,
106 category=category,
107 subreddits=resolved_subreddits,
108 sources=sources,
109 )
110
111 ALLOWED_INTENTS = {
112 "factual",
113 "product",
114 "concept",
115 "opinion",
116 "how_to",
117 "comparison",
118 "breaking_news",
119 "prediction",
120 }
121 ALLOWED_CLUSTER_MODES = {"none", "story", "workflow", "market", "debate"}
122
123 QUICK_SOURCE_PRIORITY = {
124 "factual": ["hackernews", "reddit", "x", "xquik", "youtube"],
125 "product": ["jobs", "youtube", "reddit", "x", "xquik", "tiktok"],
126 "concept": ["hackernews", "reddit", "x", "xquik", "youtube"],
127 "opinion": ["reddit", "x", "xquik", "youtube", "hackernews"],
128 "how_to": ["youtube", "reddit", "x", "xquik", "hackernews"],
129 "comparison": ["reddit", "x", "xquik", "hackernews", "youtube"],
130 "breaking_news": ["x", "xquik", "reddit", "hackernews", "youtube", "polymarket"],
131 "prediction": ["polymarket", "x", "xquik", "hackernews", "reddit", "youtube"],
132 }
133 SOURCE_PRIORITY = {
134 "factual": ["hackernews", "reddit", "x", "youtube"],
135 "product": ["jobs", "youtube", "reddit", "x", "tiktok", "hackernews"],
136 "concept": ["hackernews", "reddit", "x", "youtube"],
137 "opinion": ["reddit", "x", "stocktwits", "dripstack", "youtube", "hackernews"],
138 "how_to": ["youtube", "reddit", "x", "hackernews"],
139 "comparison": ["reddit", "x", "hackernews", "youtube"],
140 "breaking_news": ["x", "stocktwits", "reddit", "hackernews", "youtube", "polymarket"],
141 "prediction": ["polymarket", "stocktwits", "dripstack", "x", "hackernews", "reddit", "youtube"],
142 }
143 SOURCE_LIMITS = {
144 "quick": {
145 "factual": 2,
146 "product": 2,
147 "concept": 2,
148 "opinion": 2,
149 "how_to": 2,
150 "comparison": 2,
151 "breaking_news": 2,
152 "prediction": 2,
153 },
154 # "default" intentionally absent: all available sources are searched
155 # at default depth. Fusion and reranking handle quality. quick mode
156 # uses tight budgets above for latency.
157 }
158 INTENT_SOURCE_EXCLUSIONS: dict[str, set[str]] = {
159 "concept": {"polymarket"},
160 "how_to": {"polymarket"},
161 }
162 SOURCE_CAPABILITIES = {
163 "reddit": {"discussion", "social"},
164 "x": {"discussion", "social"},
165 "xquik": {"discussion", "social"},
166 "youtube": {"video", "video_longform", "discussion"},
167 "tiktok": {"video", "video_shortform", "social"},
168 "instagram": {"video", "video_shortform", "social"},
169 "hackernews": {"discussion", "link"},
170 "devto": {"discussion", "link", "reference"},
171 "v2ex": {"discussion"},
172 "juejin": {"discussion", "link", "reference"},
173 "bluesky": {"discussion", "social"},
174 "truthsocial": {"discussion", "social"},
175 "linkedin": {"discussion", "social"},
176 "polymarket": {"market"},
177 "stocktwits": {"social", "market", "finance_social"},
178 "dripstack": {"reference", "analysis", "link"},
179 "digg": {"discussion", "social", "link"},
180 "arxiv": {"reference", "analysis", "link"},
181 "techmeme": {"discussion", "link", "reference"},
182 "news_rss": {"discussion", "link", "reference"},
183 "trustpilot": {"reference", "company_signal", "social"},
184 "amazon": {"reference", "company_signal", "product_signal"},
185 "meta_ads": {"reference", "company_signal", "product_signal"},
186 "xiaohongshu": {"video", "video_shortform", "social"},
187 "telegram": {"discussion", "social"},
188 "github": {"discussion", "link"},
189 "grounding": {"web", "reference", "link"},
190 "perplexity": {"web", "reference", "analysis"},
191 "jobs": {"jobs", "company_signal", "link"},
192 "corpus": {"reference", "analysis"},
193 }
194 KNOWN_SOURCES: frozenset[str] = frozenset(SOURCE_CAPABILITIES) | {
195 "threads",
196 "pinterest",
197 "linkedin_profile",
198 }
199
200
201 def _is_identity_anchor(anchor: object) -> bool:
202 return isinstance(anchor, str) and re.search(r"\w", anchor) is not None
203
204
205 POLYMARKET_HINT_KINDS = ("team", "company", "person", "product", "other")
206 POLYMARKET_HINT_RELATIONS = ("player", "person", "product")
207 POLYMARKET_HINT_CAP = polymarket.HINT_CAP
208 POLYMARKET_HINT_NAME_MAX = 80
209
210
211 def _hint_name(value: object) -> str | None:
212 if isinstance(value, str) and value.strip() and len(value.strip()) <= POLYMARKET_HINT_NAME_MAX:
213 return value.strip()
214 return None
215
216
217 def polymarket_hints(value: object) -> dict | None:
218 """Validate and normalize a plan's ``polymarket_hints``.
219
220 Returns None when absent; raises ValueError naming the bad part otherwise.
221 """
222 if value is None:
223 return None
224 if not isinstance(value, dict):
225 raise ValueError("polymarket_hints must be an object with kind, aliases, related")
226 unknown = sorted(set(value) - {"kind", "aliases", "related"})
227 if unknown:
228 raise ValueError(f"polymarket_hints has unknown fields {unknown}")
229 hints: dict = {}
230 kind = value.get("kind")
231 if kind is not None:
232 if not isinstance(kind, str) or kind.strip().casefold() not in POLYMARKET_HINT_KINDS:
233 raise ValueError(
234 f"polymarket_hints.kind must be one of {', '.join(POLYMARKET_HINT_KINDS)}"
235 )
236 hints["kind"] = kind.strip().casefold()
237 aliases = value.get("aliases", [])
238 if (
239 not isinstance(aliases, list)
240 or len(aliases) > POLYMARKET_HINT_CAP
241 or not all(_hint_name(alias) for alias in aliases)
242 ):
243 raise ValueError(
244 f"polymarket_hints.aliases must be an array of at most {POLYMARKET_HINT_CAP} "
245 f"non-empty strings of up to {POLYMARKET_HINT_NAME_MAX} characters"
246 )
247 hints["aliases"] = [_hint_name(alias) for alias in aliases]
248 related = value.get("related", [])
249 if (
250 not isinstance(related, list)
251 or len(related) > POLYMARKET_HINT_CAP
252 or not all(
253 isinstance(entry, dict)
254 and set(entry) <= {"name", "relation"}
255 and _hint_name(entry.get("name"))
256 and isinstance(entry.get("relation"), str)
257 and entry["relation"].strip().casefold() in POLYMARKET_HINT_RELATIONS
258 for entry in related
259 )
260 ):
261 raise ValueError(
262 f"polymarket_hints.related must be an array of at most {POLYMARKET_HINT_CAP} "
263 "{name, relation} objects with relation one of "
264 + ", ".join(POLYMARKET_HINT_RELATIONS)
265 )
266 hints["related"] = [
267 {"name": _hint_name(entry["name"]), "relation": entry["relation"].strip().casefold()}
268 for entry in related
269 ]
270 return hints
271
272
273 def validate_external_plan(raw: dict) -> None:
274 """Validate explicit-plan structure before permissive sanitization.
275
276 Enum-like metadata stays permissive because direct pipeline callers rely on
277 the sanitizer to canonicalize those values.
278 """
279 if not isinstance(raw, dict):
280 raise ValueError("top-level plan must be an object")
281 for field in ("intent", "freshness_mode", "cluster_mode", "subqueries"):
282 if field not in raw:
283 raise ValueError(f"missing required field '{field}'")
284 for field in ("intent", "freshness_mode", "cluster_mode"):
285 if not isinstance(raw[field], str) or not raw[field].strip():
286 raise ValueError(f"field '{field}' must be a non-empty string")
287
288 anchors = raw.get("person_identity_anchors", [])
289 if not isinstance(anchors, list) or not all(_is_identity_anchor(a) for a in anchors):
290 raise ValueError("person_identity_anchors must be an array of non-empty strings")
291 polymarket_hints(raw.get("polymarket_hints"))
292
293 omit_sources = raw.get("omit_sources", [])
294 if not isinstance(omit_sources, list) or not all(
295 isinstance(source, str) and source in HOST_PLAN_BACKFILL_SOURCES
296 for source in omit_sources
297 ):
298 raise ValueError(
299 "omit_sources must be an array of source names eligible for host-plan backfill: "
300 + ", ".join(HOST_PLAN_BACKFILL_SOURCES)
301 )
302 omitted = set(omit_sources)
303
304 source_weights = raw.get("source_weights")
305 if source_weights is not None and not isinstance(source_weights, dict):
306 raise ValueError("field 'source_weights' must be an object when provided")
307 for source, weight in (source_weights or {}).items():
308 if (
309 not isinstance(source, str)
310 or not source.strip()
311 or isinstance(weight, bool)
312 or not isinstance(weight, (int, float))
313 ):
314 raise ValueError("field 'source_weights' must map source names to numbers")
315 subqueries = raw["subqueries"]
316 if not isinstance(subqueries, list) or not subqueries:
317 raise ValueError("field 'subqueries' must be a non-empty array")
318 for index, subquery in enumerate(subqueries):
319 if not isinstance(subquery, dict):
320 raise ValueError(f"subqueries[{index}] must be an object")
321 for field in ("search_query", "ranking_query"):
322 if not isinstance(subquery.get(field), str) or not subquery[field].strip():
323 raise ValueError(f"subqueries[{index}].{field} must be a non-empty string")
324 sources = subquery.get("sources")
325 if not isinstance(sources, list) or not sources or not all(
326 isinstance(source, str) and source.strip() for source in sources
327 ):
328 raise ValueError(f"subqueries[{index}].sources must be a non-empty string array")
329 if overlap := omitted.intersection(sources):
330 raise ValueError(
331 f"omit_sources conflicts with subqueries[{index}].sources: "
332 + ", ".join(sorted(overlap))
333 )
334 weight = subquery.get("weight")
335 if weight is not None and (
336 isinstance(weight, bool) or not isinstance(weight, (int, float))
337 ):
338 raise ValueError(f"subqueries[{index}].weight must be a number when provided")
339
340
341 DEFAULT_INTENT_CAPABILITIES = {
342 "comparison": {"discussion", "video", "web", "reference", "social", "link", "market"},
343 "how_to": {"discussion", "video", "web", "reference", "link"},
344 }
345
346
347 class DrillTargetError(ValueError):
348 """Raised when a follow-up target cannot be resolved to a report cluster."""
349
350 def __init__(self, target: str, clusters: list[schema.Cluster]) -> None:
351 candidates = ", ".join(
352 f"{index}. {cluster.title}"
353 for index, cluster in enumerate(clusters, start=1)
354 ) or "(no clusters in the cached report)"
355 super().__init__(f"No cluster matched {target!r}. Available clusters: {candidates}")
356
357
358 def _drill_cluster_text(report: schema.Report, cluster: schema.Cluster) -> str:
359 candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates}
360 parts = [cluster.title]
361 for candidate_id in cluster.candidate_ids:
362 candidate = candidates.get(candidate_id)
363 if candidate:
364 parts.extend((candidate.title, candidate.snippet))
365 return " ".join(part for part in parts if part)
366
367
368 def resolve_drill_clusters(report: schema.Report, target: str) -> list[schema.Cluster]:
369 """Resolve a 1-based cluster index or fuzzy title/entity description."""
370 cleaned = target.strip()
371 numeric = re.fullmatch(r"(?:cluster\s*)?#?(\d+)", cleaned, flags=re.IGNORECASE)
372 if numeric:
373 index = int(numeric.group(1))
374 if 1 <= index <= len(report.clusters):
375 return [report.clusters[index - 1]]
376 raise DrillTargetError(target, report.clusters)
377
378 target_entities = entity_extract.extract_text_entities(cleaned)
379 scored: list[tuple[float, schema.Cluster]] = []
380 for cluster in report.clusters:
381 cluster_text = _drill_cluster_text(report, cluster)
382 title_score = relevance.token_overlap_relevance(cleaned, cluster.title)
383 body_score = relevance.token_overlap_relevance(cleaned, cluster_text)
384 entity_score = entity_extract.entity_overlap(
385 target_entities,
386 entity_extract.extract_text_entities(cluster_text),
387 )
388 score = max(title_score, (0.75 * body_score) + (0.25 * entity_score))
389 scored.append((score, cluster))
390
391 scored.sort(key=lambda entry: entry[0], reverse=True)
392 if not scored or scored[0][0] < 0.35:
393 raise DrillTargetError(target, report.clusters)
394 return [scored[0][1]]
395
396
397 def build_drill_plan(
398 report: schema.Report,
399 target: str,
400 *,
401 clusters: list[schema.Cluster] | None = None,
402 ) -> schema.QueryPlan:
403 """Build a deep follow-up plan limited to the matched clusters' sources."""
404 matched = clusters or resolve_drill_clusters(report, target)
405 candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates}
406
407 sources: list[str] = []
408 for cluster in matched:
409 for source in cluster.sources:
410 if source and source not in sources:
411 sources.append(source)
412 for candidate_id in cluster.candidate_ids:
413 candidate = candidates.get(candidate_id)
414 if not candidate:
415 continue
416 for source in schema.candidate_sources(candidate):
417 if source and source not in sources:
418 sources.append(source)
419 cluster_titles: list[str] = []
420 representative_titles: list[str] = []
421 for cluster in matched:
422 cluster_titles.append(cluster.title)
423 for candidate_id in cluster.representative_ids:
424 candidate = candidates.get(candidate_id)
425 if candidate:
426 representative_titles.append(candidate.title)
427
428 if schema.report_has_corpus(report):
429 public_titles, public_sources = _public_drill_evidence(matched, candidates)
430 if public_titles:
431 # A cached cluster title may have come from a private representative.
432 cluster_titles = public_titles[:1]
433 representative_titles = public_titles[1:]
434 sources = list(dict.fromkeys(
435 [source for source in sources if source == "corpus" or source in public_sources]
436 + public_sources
437 ))
438 else:
439 sources = ["corpus"] if "corpus" in sources else []
440
441 if not sources:
442 raise DrillTargetError(target, report.clusters)
443
444 entity_counts: Counter[str] = Counter()
445 for title in [*cluster_titles, *representative_titles]:
446 entity_counts.update(entity_extract.extract_text_entities(title))
447 queries: list[str] = []
448 for query_text in [
449 " ".join(cluster_titles),
450 " ".join(entity for entity, _ in entity_counts.most_common(8)),
451 *representative_titles,
452 ]:
453 query_text = " ".join(query_text.split()).strip()
454 if query_text and query_text.lower() not in {item.lower() for item in queries}:
455 queries.append(query_text)
456 if len(queries) == 3:
457 break
458
459 subqueries = [
460 schema.SubQuery(
461 label=f"drill-{index}",
462 search_query=search_query,
463 ranking_query=(
464 "What deeper evidence, firsthand discussion, comments, and transcripts "
465 f"explain {search_query}?"
466 ),
467 sources=list(sources),
468 weight=1.0 if index == 1 else 0.85,
469 )
470 for index, search_query in enumerate(queries, start=1)
471 ]
472 return schema.QueryPlan(
473 intent=report.query_plan.intent,
474 freshness_mode=report.query_plan.freshness_mode,
475 cluster_mode=report.query_plan.cluster_mode,
476 raw_topic=report.topic,
477 person_identity_anchors=list(report.query_plan.person_identity_anchors),
478 person_run=report.query_plan.person_run,
479 polymarket_hints=copy.deepcopy(report.query_plan.polymarket_hints),
480 subqueries=subqueries,
481 source_weights={
482 source: report.query_plan.source_weights.get(source, 1.0)
483 for source in sources
484 },
485 notes=[
486 "drill-mode",
487 "drill-targets:" + ",".join(cluster.cluster_id for cluster in matched),
488 ],
489 )
490
491
492 def _public_drill_evidence(
493 clusters: list[schema.Cluster],
494 candidates: dict[str, schema.Candidate],
495 ) -> tuple[list[str], list[str]]:
496 titles: list[str] = []
497 sources: list[str] = []
498 for cluster in clusters:
499 for candidate_id in dict.fromkeys([*cluster.representative_ids, *cluster.candidate_ids]):
500 candidate = candidates.get(candidate_id)
501 if candidate is None:
502 continue
503 if schema.candidate_has_corpus(candidate):
504 # A fused candidate can retain public members even when its
505 # chosen title or snippet belongs to a local file.
506 for item in candidate.source_items:
507 if item.source and item.source != "corpus" and item.title.strip():
508 titles.append(item.title)
509 sources.append(item.source)
510 elif candidate.title.strip() and schema.candidate_sources(candidate):
511 titles.append(candidate.title)
512 sources.extend(schema.candidate_sources(candidate))
513 return titles, list(dict.fromkeys(sources))
514
515
516 def plan_query(
517 *,
518 topic: str,
519 available_sources: list[str],
520 requested_sources: list[str] | None,
521 depth: str,
522 provider: providers.ReasoningClient | None,
523 model: str | None,
524 context: str = "",
525 internal_subrun: bool = False,
526 deadline: float | None = None,
527 cancel: Event | None = None,
528 ) -> schema.QueryPlan:
529 """Create a query plan. Comparison queries with extractable entities use a
530 deterministic plan; other intents prefer the configured reasoning provider.
531
532 internal_subrun: when True, suppress the LAW 7 "No --plan passed" stderr
533 warning. LAW 7 targets the hosting-reasoning-model path; competitor
534 fan-out sub-runs are engine-internal and the warning is a false positive
535 there. Default False preserves the warning on every user-facing invocation
536 that ends on the deterministic fallback, including a failed internal
537 planner. On a detected agent host the CLI stops a plan-less research run
538 before this is reached, apart from its documented exemptions and the
539 ``LAST30DAYS_ALLOW_ENGINE_PLAN`` override (``last30days._law7_host_plan_gate``).
540 """
541 if _should_force_deterministic_plan(topic):
542 return _fallback_plan(
543 topic,
544 available_sources,
545 requested_sources,
546 depth,
547 note="deterministic-comparison-plan",
548 )
549 prompt = _build_prompt(topic, available_sources, requested_sources, depth)
550 if context:
551 prompt += f"\n\nCurrent context (from web search): {context}"
552 if provider and model:
553 try:
554 budget = (
555 provider.request_budget(deadline, cancel, attempts=2)
556 if deadline is not None else nullcontext()
557 )
558 with budget:
559 raw = provider.generate_json(model, prompt)
560 plan = _sanitize_plan(
561 raw, topic, available_sources, requested_sources, depth,
562 )
563 if plan.subqueries:
564 return plan
565 except (ValueError, KeyError, json.JSONDecodeError, OSError, http.HTTPError) as exc:
566 import sys
567 print(f"[Planner] LLM planning failed, using deterministic fallback: {type(exc).__name__}: {exc}", file=sys.stderr)
568 # A failed internal planner (e.g. HTTP 402, no credits) degrades
569 # the run exactly like having none, and the host may not be
570 # detectable, so the LAW 7 reminder applies here too.
571 if not internal_subrun:
572 _print_law7_reminder()
573 return _fallback_plan(
574 topic, available_sources, requested_sources, depth,
575 note=f"fallback-plan (LLM error: {type(exc).__name__})",
576 )
577 # No --plan was passed and no engine-internal provider is configured.
578 # The deterministic fallback path produces weaker plans than either the
579 # --plan path or the engine-internal LLM planner path. Surface this so
580 # the HOSTING reasoning model (Claude Code, Codex, Hermes, Gemini, etc.)
581 # realizes it is supposed to generate the plan itself and pass --plan.
582 # The word "provider" in engine messages refers to the engine's INTERNAL
583 # planner credentials - NOT a prerequisite the caller needs. If you are
584 # the hosting reasoning model, YOU are the provider. LAW 7 / 2026-04-19
585 # Hermes Agent Use Cases failure mode.
586 if not internal_subrun:
587 _print_law7_reminder()
588 return _fallback_plan(topic, available_sources, requested_sources, depth)
589
590
591 def _print_law7_reminder() -> None:
592 import sys
593 print(
594 "[Planner] No --plan passed. If you are the reasoning model hosting "
595 "this skill (Claude Code, Codex, Hermes, Gemini, or any agent runtime), "
596 "YOU ARE the planner: generate a JSON query plan yourself and pass it "
597 "via --plan. You do not need an API key or credentials; you ARE the "
598 "LLM. The deterministic fallback below is the headless/cron path only. "
599 "See LAW 7 in SKILL.md and Step 0.75 in references/research-runbook.md "
600 "for the plan schema.",
601 file=sys.stderr,
602 )
603
604
605 def _build_prompt(
606 topic: str,
607 available_sources: list[str],
608 requested_sources: list[str] | None,
609 depth: str,
610 ) -> str:
611 requested = ", ".join(requested_sources or ["auto"])
612 available = ", ".join(available_sources)
613 return f"""
614 You are the query planner for a live last-30-days research pipeline.
615
616 Topic: {topic}
617 Depth: {depth}
618 Available sources: {available}
619 Requested sources: {requested}
620
621 Return JSON only with this shape:
622 {{
623 "intent": "factual|product|concept|opinion|how_to|comparison|breaking_news|prediction",
624 "freshness_mode": "strict_recent|balanced_recent|evergreen_ok",
625 "cluster_mode": "none|story|workflow|market|debate",
626 "source_weights": {{"source_name": 0.0}},
627 "subqueries": [
628 {{
629 "label": "short label",
630 "search_query": "keyword style query for search APIs",
631 "ranking_query": "natural language rewrite for reranking",
632 "sources": ["reddit", "x", "grounding"],
633 "weight": 1.0
634 }}
635 ],
636 "person_identity_anchors": [],
637 "notes": ["optional short notes"]
638 }}
639
640 Rules:
641 - for a collision-prone person, preserve specific company/organization identity anchors explicitly supplied in the topic in person_identity_anchors; for an organization whose first word also names other people or things, use its full name (["Pace Capital"]), never a topic plus a search descriptor ("Stripe payments"); otherwise use []; never invent affiliations or use the shared name/generic role as an anchor
642 - emit 1 to 5 subqueries (how_to/opinion/product/breaking_news intents benefit from 4-5; factual/concept from 2)
643 - every subquery must include both search_query and ranking_query
644 - sources must be drawn from Available sources only
645 - use cluster_mode=none for factual or many how-to queries
646 - use strict_recent for breaking news and most predictions
647 - use debate for comparison/opinion, market for prediction, workflow for how_to, story for breaking_news
648 - ENABLEMENT: when the topic asks how to make a named tool or agent control, operate, drive, automate, or use a computer, browser, desktop, laptop, screen, or phone ("X control my computer", "get X to use my browser"), use intent=how_to and cluster_mode=workflow, never comparison. Emit 4-5 subqueries that find what gives the named tool that capability: its own built-in route, plus third-party MCP servers, CLIs, browser or desktop automation tools, and extensions it can use. Keep the named tool in two or three search_query strings, and make at least one search_query capability-only without the named tool (e.g. 'computer use MCP server', 'browser automation CLI agent').
649 - search_query should be concise and keyword-heavy
650 - ranking_query should read like a natural-language question
651 - preserve exact proper nouns and entity strings from the topic
652 - NEVER include temporal phrases in search_query: no 'last 30 days', 'recent', month names, year numbers
653 - NEVER include meta-research phrases: no 'news', 'updates', 'public appearances', 'latest developments'
654 - INTENT-MODIFIER HANDLING: when the topic contains one of {{use cases, use case, workflows, workflow, examples, tutorial, tutorials, review, reviews, comparison, applications, in practice, production, production use, how i use}}, STRIP that phrase from every search_query (keep its meaning in ranking_query). Emit 4-5 paraphrased subqueries that each express the intent differently (e.g., 'production', 'workflow OR pipeline', 'review OR experience', 'vs COMPETITOR', 'community discussion'). Broad retrieval, narrow ranking. This was the 2026-04-19 Hermes Agent Use Cases failure mode: the planner echoed "hermes agent use cases" as a literal search string and returned near-zero results because nobody posts that exact phrase.
655 - DO NOT quote the user's full topic verbatim in search_query. Quote only multi-word proper nouns like "Hermes Agent", "Claude Code", "Nous Research". Bare keywords OR'd together retrieve more than exact-phrase searches.
656 - search_query should match how content is TITLED on platforms
657 - GitHub (Issues/PRs) is best for engineering, developer tools, and open source topics: 'kanye west bully' not 'kanye west album news March 2026'
658 """.strip()
659
660
661 def _sanitize_source_weights(
662 raw_weights: object,
663 *,
664 available: set[str],
665 requested: set[str],
666 eligible_sources: list[str],
667 topic: str,
668 intent_hint: str,
669 depth: str,
670 ) -> dict[str, float]:
671 recognized_sources = KNOWN_SOURCES | available
672 recognized_raw_positive: list[float] = []
673 explicit_weights: dict[str, float] = {}
674 if isinstance(raw_weights, dict):
675 for source, weight in raw_weights.items():
676 # Skip unknown/typo source keys so they neither join the plan nor
677 # trigger normalized-weight detection; real disabled sources still
678 # count in recognized_raw_positive.
679 if source not in recognized_sources or isinstance(weight, bool):
680 continue
681 try:
682 numeric = float(weight)
683 except (TypeError, ValueError, OverflowError):
684 continue
685 if not math.isfinite(numeric):
686 continue
687 if numeric > 0:
688 recognized_raw_positive.append(numeric)
689 if source in available and (not requested or source in requested):
690 explicit_weights[source] = numeric
691 source_weights = dict(explicit_weights)
692 if not source_weights:
693 source_weights = _default_source_weights(_infer_intent(topic), eligible_sources)
694 # Preserve the base weight of 1.0 for raw unnormalized boost maps (e.g.
695 # {"reddit": 3.0} keeps Reddit's 3:1 boost over an unweighted source), and
696 # use the mean of the filtered eligible weights whenever either the filtered
697 # weights or the recognized raw plan weights already sum to ~1.0 so omitted
698 # or backfilled sources sit at the planned mean even when a real planned
699 # source is disabled.
700 basis_weights = explicit_weights if explicit_weights else source_weights
701 positive_basis = [weight for weight in basis_weights.values() if weight > 0]
702 normalized_filtered = (
703 len(positive_basis) >= 2 and abs(sum(positive_basis) - 1.0) <= 0.05
704 )
705 normalized_recognized_raw = (
706 bool(explicit_weights)
707 and len(recognized_raw_positive) >= 2
708 and abs(sum(recognized_raw_positive) - 1.0) <= 0.05
709 )
710 if positive_basis and (normalized_filtered or normalized_recognized_raw):
711 default_weight = sum(positive_basis) / len(positive_basis)
712 else:
713 default_weight = 1.0
714 for source in eligible_sources:
715 weight = default_weight * 0.6 if source == "news_rss" else default_weight
716 source_weights.setdefault(source, weight)
717 if intent_hint in DEFAULT_INTENT_CAPABILITIES and depth != "quick":
718 for source in _default_sources_for_intent(intent_hint, eligible_sources):
719 weight = default_weight * 0.6 if source == "news_rss" else default_weight
720 source_weights.setdefault(source, weight)
721 return _normalize_weights(source_weights)
722
723
724 def _sanitize_plan(
725 raw: dict,
726 topic: str,
727 available_sources: list[str],
728 requested_sources: list[str] | None,
729 depth: str,
730 *,
731 honor_plan_sources: bool = False,
732 ) -> schema.QueryPlan:
733 intent_hint = str(raw.get("intent") or _infer_intent(topic)).strip()
734 if intent_hint not in ALLOWED_INTENTS:
735 intent_hint = _infer_intent(topic)
736 # The LLM planner reads "best X to control my computer" as a comparison
737 # and plans a strict-recent debate about X. An enablement topic without an
738 # explicit comparison is a how-to; an explicit --plan keeps its intent.
739 enablement_override = (
740 not honor_plan_sources
741 and intent_hint != "how_to"
742 and _is_enablement(topic)
743 and _infer_intent(topic) == "how_to"
744 )
745 if enablement_override:
746 intent_hint = "how_to"
747 requested = set(requested_sources or [])
748 available = set(available_sources)
749 eligible_sources = [
750 source for source in available_sources
751 if (not requested or source in requested)
752 ]
753 source_weights = _sanitize_source_weights(
754 raw.get("source_weights"),
755 available=available,
756 requested=requested,
757 eligible_sources=eligible_sources,
758 topic=topic,
759 intent_hint=intent_hint,
760 depth=depth,
761 )
762
763 subqueries: list[schema.SubQuery] = []
764 raw_subqueries = raw.get("subqueries")
765 if not isinstance(raw_subqueries, list):
766 raw_subqueries = []
767 max_subqueries = _max_subqueries(intent_hint, topic)
768 # Only usable subqueries count against the cap; an external lane can be
769 # unavailable under the current configuration or source selection.
770 for index, subquery in enumerate(raw_subqueries, start=1):
771 if not isinstance(subquery, dict):
772 continue
773 raw_sources = subquery.get("sources")
774 sources = [
775 source for source in raw_sources
776 if isinstance(source, str) and source in source_weights
777 ] if isinstance(raw_sources, list) else []
778 if requested:
779 sources = [source for source in sources if source in requested]
780 sources = list(dict.fromkeys(sources))
781 if not sources:
782 if honor_plan_sources:
783 label = str(subquery.get("label") or f"q{index}")
784 log.source_log(
785 "Planner",
786 f"Skipping external-plan subquery {label}: none of its planned "
787 "sources are available under the current source configuration.",
788 tty_only=False,
789 )
790 continue
791 sources = list(source_weights)
792 if not sources:
793 continue
794 search_query = subquery.get("search_query")
795 ranking_query = subquery.get("ranking_query")
796 if not isinstance(search_query, str) or not isinstance(ranking_query, str):
797 continue
798 search_query = search_query.strip()
799 ranking_query = ranking_query.strip()
800 if not search_query or not ranking_query:
801 continue
802 raw_weight = subquery.get("weight")
803 try:
804 weight = float(raw_weight or 1.0)
805 except (TypeError, ValueError, OverflowError):
806 weight = 1.0
807 if not math.isfinite(weight):
808 weight = 1.0
809 subqueries.append(
810 schema.SubQuery(
811 label=str(subquery.get("label") or f"q{index}").strip() or f"q{index}",
812 search_query=search_query,
813 ranking_query=ranking_query,
814 sources=sources,
815 weight=max(0.05, weight),
816 )
817 )
818 if len(subqueries) == max_subqueries:
819 break
820 if (
821 depth != "quick"
822 and subqueries
823 and not honor_plan_sources
824 and intent_hint == "how_to"
825 and _is_enablement(topic)
826 and not _has_capability_subquery(subqueries, _enablement_host(topic))
827 ):
828 subqueries.extend(_enablement_subqueries(topic, list(source_weights), start=len(subqueries) + 1)[:1])
829 if depth == "quick" and subqueries:
830 subqueries = subqueries[:1]
831 if not subqueries:
832 if honor_plan_sources:
833 raise ValueError(
834 "No available planned sources remain. Enable a source named in "
835 "--plan or revise the plan/source configuration; no retrieval was started."
836 )
837 return _fallback_plan(topic, available_sources, requested_sources, depth)
838
839 intent = intent_hint
840 freshness_mode = str(raw.get("freshness_mode") or _default_freshness(intent)).strip()
841 if intent == "how_to":
842 freshness_mode = "evergreen_ok"
843 cluster_mode = str(raw.get("cluster_mode") or _default_cluster_mode(intent)).strip()
844 if enablement_override:
845 cluster_mode = _default_cluster_mode(intent)
846 if cluster_mode not in ALLOWED_CLUSTER_MODES:
847 cluster_mode = _default_cluster_mode(intent)
848
849 # --plan input was already validated strictly; a malformed field from the
850 # internal LLM planner degrades to unscoped instead of discarding its plan.
851 anchors = raw.get("person_identity_anchors")
852 if not isinstance(anchors, list):
853 anchors = []
854 try:
855 hints = polymarket_hints(raw.get("polymarket_hints"))
856 except ValueError:
857 hints = None
858 notes = raw.get("notes")
859 if not isinstance(notes, list):
860 notes = []
861 return schema.QueryPlan(
862 intent=intent,
863 freshness_mode=freshness_mode,
864 cluster_mode=cluster_mode,
865 raw_topic=topic,
866 subqueries=_normalize_subquery_weights(_unique_subquery_labels(
867 _trim_subqueries_for_depth(
868 subqueries,
869 intent,
870 depth,
871 eligible_sources,
872 requested_sources=requested_sources,
873 honor_plan_sources=honor_plan_sources,
874 )
875 )),
876 source_weights=source_weights,
877 notes=[note.strip() for note in notes if isinstance(note, str) and note.strip()]
878 + (_enablement_notes(topic) if not honor_plan_sources and intent == "how_to" and _is_enablement(topic) else []),
879 person_identity_anchors=[a.strip() for a in anchors if _is_identity_anchor(a)],
880 polymarket_hints=hints,
881 jobs_queries=jobs_story.clean_terms(raw.get("jobs_queries")),
882 )
883
884
885 def _unique_subquery_labels(subqueries: list[schema.SubQuery]) -> list[schema.SubQuery]:
886 # Retrieval, ranking, and provenance use the label as a stream key.
887 reserved = {query.label for query in subqueries}
888 used: set[str] = set()
889 out = []
890 for query in subqueries:
891 if query.label in used:
892 suffix = 2
893 while f"{query.label}-{suffix}" in reserved:
894 suffix += 1
895 query = replace(query, label=f"{query.label}-{suffix}")
896 reserved.add(query.label)
897 used.add(query.label)
898 out.append(query)
899 return out
900
901
902 def _normalize_subquery_weights(subqueries: list[schema.SubQuery]) -> list[schema.SubQuery]:
903 total = sum(subquery.weight for subquery in subqueries) or 1.0
904 return [
905 schema.SubQuery(
906 label=subquery.label,
907 search_query=subquery.search_query,
908 ranking_query=subquery.ranking_query,
909 sources=subquery.sources,
910 weight=subquery.weight / total,
911 )
912 for subquery in subqueries
913 ]
914
915
916 def _normalize_weights(weights: dict[str, float]) -> dict[str, float]:
917 total = sum(max(weight, 0.0) for weight in weights.values()) or 1.0
918 return {
919 source: max(weight, 0.0) / total
920 for source, weight in weights.items()
921 }
922
923
924 def _trim_subqueries_for_depth(
925 subqueries: list[schema.SubQuery],
926 intent: str,
927 depth: str,
928 available_sources: list[str],
929 requested_sources: list[str] | None = None,
930 honor_plan_sources: bool = False,
931 ) -> list[schema.SubQuery]:
932 # At non-quick depth, expand sources: use capability routing for intents
933 # that define it, or all available sources otherwise. The LLM planner may
934 # assign narrow source lists; we override to let fusion decide quality.
935 # Operator-supplied --plan is a contract: keep per-subquery sources.
936 if depth != "quick" and not honor_plan_sources:
937 expanded_sources = _default_sources_for_intent(intent, available_sources)
938 # Explicit --search sources are a user override: intent routing must not drop them.
939 expanded_sources += [
940 source for source in available_sources
941 if source in (requested_sources or []) and source not in expanded_sources
942 ]
943 return [
944 schema.SubQuery(
945 label=subquery.label,
946 search_query=subquery.search_query,
947 ranking_query=subquery.ranking_query,
948 sources=expanded_sources,
949 weight=subquery.weight,
950 )
951 for subquery in subqueries
952 ]
953 limits = SOURCE_LIMITS.get(depth)
954 if not limits:
955 return subqueries
956 priority_table = QUICK_SOURCE_PRIORITY
957 priority = priority_table.get(intent, priority_table["breaking_news"])
958 limit = limits.get(intent, 3)
959 ranked_sources = [source for source in priority if source in available_sources]
960 if not ranked_sources:
961 ranked_sources = list(available_sources)
962 trimmed = []
963 for subquery in subqueries:
964 # Quick depth only reaches this block. Honor the plan's explicit
965 # per-subquery sources: prefer priority-ranked plan sources first, then
966 # append any plan sources absent from the priority table (e.g.
967 # instagram). Explicit --search sources are user overrides, so they get
968 # first claim on the quick slots when present. The final list remains
969 # capped to the quick-depth limit.
970 plan_sources = [s for s in ranked_sources if s in subquery.sources]
971 for source in subquery.sources:
972 if source not in plan_sources:
973 plan_sources.append(source)
974 if not plan_sources:
975 plan_sources = ranked_sources[:limit]
976 preferred_sources: list[str] = []
977 if requested_sources:
978 for source in requested_sources:
979 if (
980 source in available_sources
981 and source in subquery.sources
982 and source not in preferred_sources
983 ):
984 preferred_sources.append(source)
985 if len(preferred_sources) >= limit:
986 break
987 for source in plan_sources:
988 if len(preferred_sources) >= limit:
989 break
990 if source not in preferred_sources:
991 preferred_sources.append(source)
992 trimmed.append(
993 schema.SubQuery(
994 label=subquery.label,
995 search_query=subquery.search_query,
996 ranking_query=subquery.ranking_query,
997 sources=preferred_sources,
998 weight=subquery.weight,
999 )
1000 )
1001 return trimmed
1002
1003
1004 def _fallback_plan(
1005 topic: str,
1006 available_sources: list[str],
1007 requested_sources: list[str] | None,
1008 depth: str,
1009 note: str = "fallback-plan",
1010 ) -> schema.QueryPlan:
1011 intent = _infer_intent(topic)
1012 available_set = set(available_sources)
1013 if requested_sources:
1014 eligible = list(dict.fromkeys(
1015 s for s in requested_sources if s in available_set
1016 ))
1017 effective_requested: list[str] | None = eligible
1018 else:
1019 eligible = list(dict.fromkeys(available_sources))
1020 effective_requested = None
1021
1022 # Hebrew-language topics: elevate web search (grounding) to the front of
1023 # the source list since Reddit/HN/GitHub are English-dominant platforms.
1024 # Grounding covers Ynet, Walla, Mako, N12 etc. if a web search key is set.
1025 # Only reorder when grounding is already eligible — never inject it into an
1026 # explicit --search list that omitted grounding.
1027 if detect_language(topic) == 'he' and 'grounding' in eligible:
1028 eligible = ['grounding'] + [s for s in eligible if s != 'grounding']
1029 if effective_requested is not None:
1030 effective_requested = list(eligible)
1031
1032 allowed_sources = eligible
1033 if not allowed_sources:
1034 return schema.QueryPlan(
1035 intent=intent,
1036 freshness_mode=_default_freshness(intent),
1037 cluster_mode=_default_cluster_mode(intent),
1038 raw_topic=topic,
1039 subqueries=[],
1040 source_weights={},
1041 notes=[note] + (_enablement_notes(topic) if intent == "how_to" and _is_enablement(topic) else []),
1042 )
1043 source_weights = _default_source_weights(intent, allowed_sources)
1044 core = query.extract_core_subject(topic, max_words=6, strip_suffixes=True)
1045 base_search = _keyword_query(topic, core)
1046 base_ranking = _ranking_query(topic, core)
1047
1048 subqueries = [schema.SubQuery(
1049 label="primary",
1050 search_query=base_search,
1051 ranking_query=base_ranking,
1052 sources=list(source_weights),
1053 weight=1.0,
1054 )]
1055
1056 if depth != "quick" and intent == "comparison":
1057 entities = _comparison_entities(topic)
1058 if entities:
1059 for index, entity in enumerate(entities, start=1):
1060 subqueries.append(
1061 schema.SubQuery(
1062 label=f"entity-{index}",
1063 search_query=entity,
1064 ranking_query=f"What recent evidence from the last 30 days is most relevant to {entity} in the comparison '{topic}'?",
1065 sources=list(source_weights),
1066 weight=0.65,
1067 )
1068 )
1069 elif depth != "quick" and intent == "prediction":
1070 subqueries.append(
1071 schema.SubQuery(
1072 label="odds",
1073 search_query=f"{base_search} odds forecast",
1074 ranking_query=f"What are the current odds, forecasts, or market signals about {topic}?",
1075 sources=[source for source in source_weights if source in {"polymarket", "grounding", "x", "reddit"}] or list(source_weights),
1076 weight=0.7,
1077 )
1078 )
1079 elif depth != "quick" and intent == "breaking_news":
1080 subqueries.append(
1081 schema.SubQuery(
1082 label="reaction",
1083 search_query=f"{base_search} reaction update",
1084 ranking_query=f"What new reactions or follow-up reporting from the last 30 days matter for {topic}?",
1085 sources=[source for source in source_weights if source in {"x", "reddit", "grounding", "hackernews"}] or list(source_weights),
1086 weight=0.7,
1087 )
1088 )
1089
1090 if depth != "quick" and intent == "how_to" and _is_enablement(topic):
1091 subqueries.extend(_enablement_subqueries(topic, list(source_weights)))
1092
1093 # Intent-modifier fanout: when topic contains a phrase like "use cases",
1094 # "workflows", "examples", "review" (see _INTENT_MODIFIER_PATTERNS),
1095 # paraphrase the intent across 3 extra subqueries rather than echoing
1096 # the literal phrase. Fixes 2026-04-19 Hermes Agent Use Cases failure.
1097 # Excluded for comparison/prediction since those already have dedicated
1098 # fanout (entity-per-subquery / odds).
1099 if depth != "quick" and intent not in {"comparison", "prediction"} and _has_intent_modifier(topic):
1100 subqueries.extend(_intent_modifier_subqueries(topic, core, base_search, source_weights))
1101
1102 return schema.QueryPlan(
1103 intent=intent,
1104 freshness_mode=_default_freshness(intent),
1105 cluster_mode=_default_cluster_mode(intent),
1106 raw_topic=topic,
1107 subqueries=_normalize_subquery_weights(
1108 _trim_subqueries_for_depth(
1109 subqueries[:_max_subqueries(intent, topic)],
1110 intent,
1111 depth,
1112 list(source_weights),
1113 requested_sources=effective_requested,
1114 )
1115 ),
1116 source_weights=_normalize_weights(source_weights),
1117 notes=[note] + (_enablement_notes(topic) if intent == "how_to" and _is_enablement(topic) else []),
1118 )
1119
1120
1121 _SLASH_COMPARISON = re.compile(r"\b[A-Z][a-z]{2,}(?:/[A-Z][a-z]{2,})+\b")
1122
1123
1124 # Plan notes marking a topic that asks how to give a named tool (the host) a
1125 # capability. Rerank reads them to keep capability-only search results, which
1126 # name the tool that delivers the capability rather than the host, out of the
1127 # entity cap.
1128 ENABLEMENT_NOTE = "enablement"
1129 ENABLEMENT_HOST_NOTE = "enablement-host:"
1130 _HOST_FILLER = frozenset(
1131 "a an the best top good which what how to can i we get make let have that "
1132 "who is are for my your our some any".split()
1133 )
1134 _GENERIC_HOST = frozenset("ai agent agents bot bots tool tools app apps assistant llm model".split())
1135
1136 _DEVICE = r"(?:my|the|your|our)\s+(?:own\s+)?(?:computer|mac|pc|desktop|laptop|browser|screen|phone|terminal)s?\b"
1137 # Mirrors the hosted service worker's detect_enablement_intent.
1138 # A tool acting on a device the person owns: "grok bot control my computer",
1139 # "agent that automates the browser". Plain "use the browser" is ordinary use.
1140 _ENABLEMENT_TARGET_RE = re.compile(
1141 r"\b(?P<verb>control(?:s|ling)?|operat(?:e|es|ing)|automat(?:e|es|ing))\s+" + _DEVICE,
1142 re.IGNORECASE,
1143 )
1144 # A named tool made to act on the device: "get claude to control my browser",
1145 # "make chatgpt use my mac". The lookahead keeps people and idioms out, as in
1146 # "let my kid use the phone", "make kids use the computer", "make sure I use".
1147 _ENABLEMENT_AGENT_RE = re.compile(
1148 r"\b(?:get|make|let|have)\s+"
1149 r"(?!(?:to|me|us|them|you|sure|my|your|our|his|her|their|the\s+most|kids?|children|teens?|users?|people|customers?|employees?|students?|staff|team)\b)"
1150 r"[\w.-]+(?:\s+[\w.-]+){0,2}?\s+(?:to\s+)?"
1151 r"(?P<verb>control(?:s|ling)?|operat(?:e|es|ing)|drives?|automat(?:e|es|ing)|uses?)\s+" + _DEVICE,
1152 re.IGNORECASE,
1153 )
1154 # Asking for news about device control is not asking how to enable it. Bare
1155 # "latest" or "released" stays allowed: "get the latest Claude to use my mac".
1156 _ENABLEMENT_NEWS_RE = re.compile(
1157 r"\b(?:news|headlines?|announce(?:d|s|ment)|breaking"
1158 r"|just\s+(?:shipped|launched|released)"
1159 r"|(?:launch(?:ed|es)|release[sd]|unveil(?:ed|s)|ships)\s+(?:a|an|its|new)\b)",
1160 re.IGNORECASE,
1161 )
1162 # A threat as the actor ("malware controlling my browser") is a security topic.
1163 # Only words before the verb count, so "...my browser without malware" is fine.
1164 _ENABLEMENT_THREAT_RE = re.compile(
1165 r"\b(?:malware|virus(?:es)?|spyware|ransomware|trojans?|keyloggers?|rootkits?"
1166 r"|hack(?:ed|er|ers)|scam(?:s|mers?)?|attackers?|someone|somebody|stranger)\b",
1167 re.IGNORECASE,
1168 )
1169
1170
1171 def _is_enablement(topic: str) -> bool:
1172 """The topic asks how to give a named tool a capability, such as
1173 controlling the person's computer. That is a how-to, not a comparison."""
1174 if _ENABLEMENT_NEWS_RE.search(topic):
1175 return False
1176 for pattern in (_ENABLEMENT_TARGET_RE, _ENABLEMENT_AGENT_RE):
1177 for match in pattern.finditer(topic):
1178 if not _ENABLEMENT_THREAT_RE.search(topic, 0, match.start("verb")):
1179 return True
1180 return False
1181
1182
1183 def _enablement_host(topic: str) -> str:
1184 """The named tool an enablement topic wants to give a capability, as one
1185 lowercase token ("grok" for "best Grok AI bot to control my computer"), or
1186 "" when the topic names no distinctive tool ("agent that automates the
1187 desktop")."""
1188 match = _ENABLEMENT_AGENT_RE.search(topic) or _ENABLEMENT_TARGET_RE.search(topic)
1189 if not match:
1190 return ""
1191 if match.re is _ENABLEMENT_AGENT_RE:
1192 words = re.findall(r"[\w.-]+", match.group(0).lower())[1:]
1193 else:
1194 words = re.findall(r"[\w.-]+", topic[: match.start()].lower())
1195 words = [word for word in words if word not in _HOST_FILLER]
1196 if not words or words[0] in _GENERIC_HOST:
1197 return ""
1198 return words[0]
1199
1200
1201 def _enablement_notes(topic: str) -> list[str]:
1202 host = _enablement_host(topic)
1203 return [ENABLEMENT_NOTE] + ([f"{ENABLEMENT_HOST_NOTE}{host}"] if host else [])
1204
1205
1206 def _enablement_capability_queries(topic: str) -> list[str]:
1207 """Capability-only searches for an enablement topic, without the named tool.
1208
1209 General tools (MCP servers, agent CLIs) rarely appear in posts that name
1210 the host, so the plan searches for the capability itself as well.
1211 """
1212 match = _ENABLEMENT_TARGET_RE.search(topic) or _ENABLEMENT_AGENT_RE.search(topic)
1213 device = match.group(0).lower() if match else ""
1214 if "browser" in device:
1215 return ["browser automation MCP server", "browser automation CLI for AI agents"]
1216 if "phone" in device:
1217 return ["phone automation MCP server for AI agents", "AI agent control phone app automation"]
1218 if "terminal" in device:
1219 return ["terminal MCP server for AI agents", "AI agent shell CLI tool"]
1220 if "mac" in device.split():
1221 return ["macOS computer use MCP server", "macOS automation CLI for AI agents"]
1222 return ["computer use MCP server", "desktop automation CLI for AI agents"]
1223
1224
1225 def _has_capability_subquery(subqueries, host: str) -> bool:
1226 # Must leave out the host: fusion.capability_labels ignores searches that name it.
1227 return any(
1228 re.search(r"\b(?:mcp|cli|computer[- ]use|automation)\b", sq.search_query, re.IGNORECASE)
1229 and not (host and re.search(rf"\b{re.escape(host)}", sq.search_query, re.IGNORECASE))
1230 for sq in subqueries
1231 )
1232
1233
1234 def _enablement_subqueries(topic: str, sources: list[str], start: int = 1) -> list[schema.SubQuery]:
1235 return [
1236 schema.SubQuery(
1237 label=f"capability-{index}",
1238 search_query=search,
1239 ranking_query=f"Which tools, MCP servers, or CLIs give an AI agent this capability, as asked in '{topic}'?",
1240 sources=list(sources),
1241 weight=0.7,
1242 )
1243 for index, search in enumerate(_enablement_capability_queries(topic), start=start)
1244 ]
1245
1246
1247 def _infer_intent(topic: str) -> str:
1248 text = topic.lower().strip()
1249 if re.search(r"\b(vs|versus|compare|compared to|difference between)\b", text):
1250 return "comparison"
1251 # Slash-separated proper nouns: "React/Vue/Svelte" (not URLs, not acronyms like CI/CD or I/O)
1252 if not re.search(r"https?://", topic) and _SLASH_COMPARISON.search(topic):
1253 return "comparison"
1254 if re.search(r"\b(odds|predict|prediction|forecast|chance|probability|will .* win)\b", text):
1255 return "prediction"
1256 if _is_enablement(topic) or re.search(r"\b(how to|tutorial|guide|setup|step by step|deploy|install)\b", text):
1257 return "how_to"
1258 if re.search(r"\b(what is|what are|who is|who acquired|when did|parameter count|release date)\b", text):
1259 return "factual"
1260 if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
1261 return "opinion"
1262 if re.search(r"\b(latest|news|announced|just shipped|launched|released|update)\b", text):
1263 return "breaking_news"
1264 if re.search(r"\b(pricing|feature|features|best .* for|top .* for)\b", text):
1265 return "product"
1266 if re.search(r"\b(explain|concept|protocol|architecture|what does)\b", text):
1267 return "concept"
1268 if re.search(r"\b(tournament|championship|playoffs|march madness|world cup|olympics|super bowl|final four|ceremony|awards|keynote)\b", text):
1269 return "breaking_news"
1270 # Recency signals take priority when nothing more specific matched.
1271 if re.search(r"\b(trending|this week|right now|today|this month)\b", text):
1272 return "breaking_news"
1273 # Default changed from "breaking_news" to "concept" on 2026-04-19 after
1274 # the Hermes Agent Use Cases failure: unclassified topics were getting
1275 # strict_recent freshness, which over-weighted the last 7 days and
1276 # under-weighted older relevant material. "concept" defaults to
1277 # evergreen_ok freshness, a safer posture for unknown topics.
1278 return "concept"
1279
1280
1281 def _default_freshness(intent: str) -> str:
1282 if intent in {"breaking_news", "prediction"}:
1283 return "strict_recent"
1284 if intent in {"concept", "how_to"}:
1285 return "evergreen_ok"
1286 return "balanced_recent"
1287
1288
1289 def _default_cluster_mode(intent: str) -> str:
1290 return {
1291 "breaking_news": "story",
1292 "comparison": "debate",
1293 "opinion": "debate",
1294 "prediction": "market",
1295 "how_to": "workflow",
1296 "factual": "none",
1297 "product": "none",
1298 "concept": "none",
1299 }.get(intent, "none")
1300
1301
1302 def _default_source_weights(intent: str, sources: list[str]) -> dict[str, float]:
1303 base = {source: 1.0 for source in sources}
1304 if "news_rss" in base:
1305 base["news_rss"] = 0.75 if intent == "breaking_news" else 0.55
1306 if intent == "prediction":
1307 for source, bonus in {"polymarket": 2.5, "x": 1.3}.items():
1308 if source in base:
1309 base[source] += bonus
1310 elif intent == "breaking_news":
1311 for source, bonus in {"x": 1.5, "reddit": 1.3, "hackernews": 0.8}.items():
1312 if source in base:
1313 base[source] += bonus
1314 elif intent == "how_to":
1315 for source, bonus in {"youtube": 2.0, "hackernews": 0.8}.items():
1316 if source in base:
1317 base[source] += bonus
1318 elif intent == "factual":
1319 for source, bonus in {"reddit": 0.8, "x": 0.5}.items():
1320 if source in base:
1321 base[source] += bonus
1322 elif intent == "product":
1323 for source, bonus in {"jobs": 0.8, "youtube": 0.5}.items():
1324 if source in base:
1325 base[source] += bonus
1326 return base
1327
1328
1329 def _keyword_query(topic: str, core: str) -> str:
1330 """Build a search_query string for the deterministic fallback.
1331
1332 Quote ONLY title-cased multi-word proper nouns ("Hermes Agent",
1333 "Claude Code", "Nous Research") so platform search engines preserve the
1334 name as a phrase. Hyphenated compounds and lowercase terms are left as
1335 bare keywords, which broadens retrieval instead of narrowing it.
1336
1337 Prior behavior quoted the entire compound including the user's typed
1338 topic, producing searches like `"Hermes Agent Actual Use Cases" hermes agent actual`
1339 that returned near-zero matches on X and Reddit because nobody posts
1340 that exact phrase. See 2026-04-19 Hermes Agent Use Cases failure.
1341 """
1342 compounds = query.extract_compound_terms(topic)
1343 # Only quote short (2-3 word) capitalized/brand proper nouns. Hyphenated
1344 # compounds go unquoted so platform tokenizers can split and match.
1345 title_cased = [
1346 term for term in compounds
1347 if query.COMPOUND_ENTITY_PHRASE_RE.fullmatch(term)
1348 ]
1349 selected = title_cased[:2]
1350 quoted = " ".join(f'"{term}"' for term in selected)
1351 remainder = core.strip() or topic.strip()
1352 # Drop words already carried by a quoted phrase. Emitting both produced
1353 # '"Peter Steinberger" peter steinberger steipete', which reads to a
1354 # provider as the phrase AND each of its words again -- strictly narrower
1355 # than the phrase alone, and on X it degraded to a bare token conjunction
1356 # once the quotes were stripped downstream. Distinct tokens (here
1357 # "steipete") are preserved.
1358 if selected and remainder:
1359 phrase_words = {
1360 word.lower()
1361 for term in selected
1362 for word in term.split()
1363 }
1364 remainder = " ".join(
1365 word for word in remainder.split()
1366 if word.strip('"').lower() not in phrase_words
1367 )
1368 keywords = [quoted.strip(), remainder.strip()]
1369 return " ".join(part for part in keywords if part).strip()
1370
1371
1372 def _ranking_query(topic: str, core: str) -> str:
1373 if topic.strip().endswith("?"):
1374 return topic.strip()
1375 if core and core.lower() != topic.lower():
1376 return f"What recent evidence from the last 30 days is most relevant to {topic}, especially about {core}?"
1377 return f"What recent evidence from the last 30 days is most relevant to {topic}?"
1378
1379
1380 _TRAILING_CONTEXT = re.compile(
1381 r"\s+\b(?:for|in|on|at|to|with|about|from|by|during|since|after|before|using|via)\b.*$",
1382 re.I,
1383 )
1384
1385
1386 def _comparison_entities(topic: str, *, uncapped: bool = False) -> list[str]:
1387 """Split a comparison topic into entity names.
1388
1389 Caps at ``competitors.COMPARISON_ENTITY_MAX`` unless ``uncapped`` (caller
1390 truncates and may warn about dropped entities).
1391
1392 Standalone comparator tokens are syntax, including repeated tokens.
1393 Compact ``vs.`` separates entities only after a nonempty left entity.
1394 """
1395 if _infer_intent(topic) != "comparison":
1396 return []
1397
1398 # "difference between X and Y" -> "X vs Y" (replace "and" only in this context)
1399 normalized = re.sub(
1400 r"\bdifference between\s+(.+?)\s+and\s+",
1401 r"\1 vs ",
1402 topic,
1403 flags=re.I,
1404 )
1405 normalized = re.sub(r"\b(compared to)\b", " vs ", normalized, flags=re.I)
1406 separator = r"(?<!\S)(?:(?P<standalone>vs\.?|versus)(?!\S)|vs\.(?=\S))"
1407 if not re.search(separator, normalized, flags=re.I):
1408 if re.search(r"https?://", normalized):
1409 return []
1410 normalized = _SLASH_COMPARISON.sub(
1411 lambda match: match.group(0).replace("/", " vs "), normalized,
1412 )
1413 trim = " \t\r\n?.,:;!()[]{}\"'"
1414 parts = []
1415 part_start = 0
1416 for match in re.finditer(separator, normalized, flags=re.I):
1417 part = normalized[part_start:match.start()].strip(trim)
1418 if part:
1419 parts.append(part)
1420 if part or match.group("standalone") is not None:
1421 part_start = match.end()
1422 last_part = normalized[part_start:].strip(trim)
1423 if last_part:
1424 parts.append(last_part)
1425 # Strip trailing context from parts ("Svelte for frontend in 2026" -> "Svelte")
1426 if len(parts) < 2:
1427 return []
1428 parts = [_TRAILING_CONTEXT.sub("", part).strip() or part for part in parts]
1429 deduped: list[str] = []
1430 for part in parts:
1431 if part and part not in deduped:
1432 deduped.append(part)
1433 if uncapped:
1434 return deduped
1435 return deduped[: competitors.COMPARISON_ENTITY_MAX]
1436
1437
1438 def _should_force_deterministic_plan(topic: str) -> bool:
1439 return _infer_intent(topic) == "comparison" and len(_comparison_entities(topic)) >= 2
1440
1441
1442 _INTENT_MODIFIER_PATTERNS = (
1443 "use cases", "use case", "workflows", "workflow",
1444 "examples", "example", "tutorial", "tutorials",
1445 "review", "reviews", "comparison", "applications",
1446 "in practice", "production use", "production",
1447 "how i use",
1448 )
1449
1450
1451 def _has_intent_modifier(topic: str) -> bool:
1452 """Return True if the topic contains an intent modifier phrase.
1453
1454 See 2026-04-19 Hermes Agent Use Cases failure: a literal "Hermes Agent
1455 use cases" search returns near-zero matches because nobody posts that
1456 exact phrase. Intent modifiers should be stripped from search_query
1457 and paraphrased across multiple subqueries.
1458 """
1459 text = topic.lower()
1460 return any(pattern in text for pattern in _INTENT_MODIFIER_PATTERNS)
1461
1462
1463 def _intent_modifier_subqueries(
1464 topic: str,
1465 core: str,
1466 base_search: str,
1467 source_weights: dict[str, float],
1468 ) -> list[schema.SubQuery]:
1469 """Produce paraphrased subqueries for intent-modifier topics.
1470
1471 The deterministic fallback used to echo the user's literal phrase
1472 (e.g., "hermes agent use cases") into every search_query. This helper
1473 fans out 3 extra subqueries that each express the intent differently
1474 so retrieval pulls a broader corpus for reranking.
1475 """
1476 entity = core or topic.strip()
1477 sources = list(source_weights)
1478 return [
1479 schema.SubQuery(
1480 label="workflows",
1481 search_query=f"{entity} workflow pipeline",
1482 ranking_query=f"What real-world workflows or pipelines are people running with {entity}?",
1483 sources=sources,
1484 weight=0.6,
1485 ),
1486 schema.SubQuery(
1487 label="production",
1488 search_query=f"{entity} production real-world",
1489 ranking_query=f"What production deployments or real-world use cases of {entity} are people describing?",
1490 sources=sources,
1491 weight=0.55,
1492 ),
1493 schema.SubQuery(
1494 label="experience",
1495 search_query=f"{entity} experience review",
1496 ranking_query=f"What hands-on experience reports or reviews of {entity} exist in the last 30 days?",
1497 sources=sources,
1498 weight=0.5,
1499 ),
1500 ]
1501
1502
1503 def _max_subqueries(intent: str, topic: str | None = None) -> int:
1504 # how_to/opinion/product/breaking_news/prediction benefit from 4-5
1505 # paraphrased subqueries when the topic carries an intent modifier
1506 # (use cases, workflows, examples, review, etc.). See 2026-04-19
1507 # Hermes Agent Use Cases failure: prior cap of 3 produced near-literal
1508 # echoes of the topic instead of a paraphrase fanout.
1509 if intent == "comparison":
1510 # primary + one dedicated subquery per entity (up to COMPARISON_ENTITY_MAX)
1511 return competitors.COMPARISON_ENTITY_MAX + 1
1512 # Intent-modifier topics get headroom for paraphrase fanout even when
1513 # the intent itself is factual/concept. Without this, a "Hermes Agent
1514 # use cases" query (classified "concept" after the 2026-04-19 default
1515 # change) would be capped at 2 and drop the fanout.
1516 if topic and _has_intent_modifier(topic):
1517 return 5
1518 if intent in {"factual", "concept"}:
1519 return 2
1520 return 5
1521
1522
1523 def _default_sources_for_intent(intent: str, available_sources: list[str]) -> list[str]:
1524 if intent == "how_to":
1525 sources = _how_to_sources(available_sources)
1526 else:
1527 target_capabilities = DEFAULT_INTENT_CAPABILITIES.get(intent)
1528 if not target_capabilities:
1529 sources = list(available_sources)
1530 else:
1531 matched = [
1532 source
1533 for source in available_sources
1534 if SOURCE_CAPABILITIES.get(source, set()) & target_capabilities
1535 ]
1536 sources = matched or list(available_sources)
1537 excluded = INTENT_SOURCE_EXCLUSIONS.get(intent, set())
1538 if excluded:
1539 filtered = [s for s in sources if s not in excluded]
1540 return filtered or sources
1541 return sources
1542
1543
1544 def _how_to_sources(available_sources: list[str]) -> list[str]:
1545 """Pick one source per role: web/reference, video (prefer longform), discussion."""
1546 selected: set[str] = set()
1547 has_video = False
1548 # Order matters: web first, then longform video, generic video, discussion.
1549 role_capabilities = [
1550 {"web", "reference"},
1551 {"video_longform"},
1552 {"video"},
1553 {"discussion"},
1554 ]
1555 for role in role_capabilities:
1556 is_video_role = role & {"video", "video_longform"}
1557 if is_video_role and has_video:
1558 continue
1559 for source in available_sources:
1560 if source in selected:
1561 continue
1562 if SOURCE_CAPABILITIES.get(source, set()) & role:
1563 selected.add(source)
1564 if is_video_role:
1565 has_video = True
1566 break
1567 # After core role-based selection, include remaining sources with any
1568 # how_to-relevant capability (video, discussion, web, reference, link).
1569 how_to_caps = DEFAULT_INTENT_CAPABILITIES.get("how_to", set())
1570 for source in available_sources:
1571 if source not in selected and SOURCE_CAPABILITIES.get(source, set()) & how_to_caps:
1572 selected.add(source)
1573 if not selected:
1574 return list(available_sources)
1575 return [source for source in available_sources if source in selected]
1576
1576 lines PYTHON