返回 last30days-skill
test_planner_v3.py
根目录 / tests / test_planner_v3.py
1 import unittest
2
3 from lib import fusion, planner
4
5
6 class PlannerV3Tests(unittest.TestCase):
7 def test_external_plan_rejects_valid_json_with_wrong_structure(self):
8 with self.assertRaisesRegex(ValueError, "intent"):
9 planner.validate_external_plan({"queries": {"web": ["Berlin"]}})
10
11 def test_external_plan_accepts_documented_shape_without_source_weights(self):
12 planner.validate_external_plan(
13 {
14 "intent": "breaking_news",
15 "freshness_mode": "strict_recent",
16 "cluster_mode": "story",
17 "subqueries": [
18 {
19 "label": "primary",
20 "search_query": "kanye west",
21 "ranking_query": "What happened with Kanye West?",
22 "sources": ["reddit", "x"],
23 "weight": 1.0,
24 }
25 ],
26 }
27 )
28
29 def test_external_plan_rejects_non_numeric_weight(self):
30 base_plan = {
31 "intent": "breaking_news",
32 "freshness_mode": "strict_recent",
33 "cluster_mode": "story",
34 "subqueries": [
35 {
36 "label": "primary",
37 "search_query": "kanye west",
38 "ranking_query": "What happened with Kanye West?",
39 "sources": ["reddit", "x"],
40 "weight": 1.0,
41 }
42 ],
43 }
44 for invalid_weight in ("heavy", True):
45 with self.subTest(subquery_weight=invalid_weight):
46 invalid_plan = dict(base_plan)
47 invalid_plan["subqueries"] = [
48 dict(base_plan["subqueries"][0], weight=invalid_weight)
49 ]
50 with self.assertRaisesRegex(ValueError, "weight"):
51 planner.validate_external_plan(invalid_plan)
52
53 invalid_source_weight = dict(base_plan, source_weights={"x": True})
54 with self.assertRaisesRegex(ValueError, "source_weights"):
55 planner.validate_external_plan(invalid_source_weight)
56
57 def test_default_how_to_expands_past_llm_narrow_source_weights(self):
58 raw = {
59 "intent": "how_to",
60 "freshness_mode": "balanced_recent",
61 "cluster_mode": "workflow",
62 "source_weights": {"hackernews": 0.7, "reddit": 0.3},
63 "subqueries": [
64 {
65 "label": "primary",
66 "search_query": "deploy app to Fly.io guide",
67 "ranking_query": "How do I deploy an app to Fly.io?",
68 "sources": ["hackernews"],
69 "weight": 1.0,
70 }
71 ],
72 }
73 plan = planner._sanitize_plan(
74 raw,
75 "how to deploy on Fly.io",
76 ["reddit", "x", "youtube", "hackernews"],
77 None,
78 "default",
79 )
80 sources = plan.subqueries[0].sources
81 # how_to capability routing selects video + discussion
82 self.assertIn("reddit", sources)
83 self.assertIn("youtube", sources)
84 self.assertIn("reddit", plan.source_weights)
85 self.assertIn("youtube", plan.source_weights)
86 self.assertEqual("evergreen_ok", plan.freshness_mode)
87
88 def test_comparison_uses_deterministic_plan_and_preserves_entities(self):
89 plan = planner.plan_query(
90 topic="openclaw vs nanoclaw vs ironclaw",
91 available_sources=["reddit", "x", "youtube", "hackernews", "polymarket"],
92 requested_sources=None,
93 depth="default",
94 provider=object(),
95 model="ignored",
96 )
97 self.assertEqual("comparison", plan.intent)
98 self.assertEqual(["deterministic-comparison-plan"], plan.notes)
99 self.assertEqual(4, len(plan.subqueries))
100 joined_queries = "\n".join(subquery.search_query for subquery in plan.subqueries).lower()
101 self.assertIn("openclaw", joined_queries)
102 self.assertIn("nanoclaw", joined_queries)
103 self.assertIn("ironclaw", joined_queries)
104
105 def test_fallback_plan_emits_dual_query_fields(self):
106 plan = planner.plan_query(
107 topic="codex vs claude code",
108 available_sources=["reddit", "x"],
109 requested_sources=None,
110 depth="default",
111 provider=None,
112 model=None,
113 )
114 self.assertEqual("comparison", plan.intent)
115 self.assertGreaterEqual(len(plan.subqueries), 2)
116 for subquery in plan.subqueries:
117 self.assertTrue(subquery.search_query)
118 self.assertTrue(subquery.ranking_query)
119
120 def test_factual_topic_uses_no_cluster_mode(self):
121 plan = planner.plan_query(
122 topic="what is the parameter count of claude code",
123 available_sources=["reddit", "hackernews"],
124 requested_sources=None,
125 depth="default",
126 provider=None,
127 model=None,
128 )
129 self.assertEqual("factual", plan.intent)
130 self.assertEqual("none", plan.cluster_mode)
131
132 def test_quick_mode_collapses_fallback_to_single_subquery(self):
133 plan = planner.plan_query(
134 topic="codex vs claude code",
135 available_sources=["reddit", "x"],
136 requested_sources=None,
137 depth="quick",
138 provider=None,
139 model=None,
140 )
141 self.assertEqual("comparison", plan.intent)
142 self.assertEqual(1, len(plan.subqueries))
143 self.assertEqual(["reddit", "x"], plan.subqueries[0].sources)
144
145 def test_operator_plan_keeps_per_subquery_sources_at_default_and_deep(self):
146 # Issue #1073: operator --plan sources must not be replaced with the
147 # full available list outside --quick.
148 raw = {
149 "intent": "opinion",
150 "freshness_mode": "balanced_recent",
151 "cluster_mode": "debate",
152 "subqueries": [{
153 "label": "primary",
154 "search_query": "late diagnosed autism adults",
155 "ranking_query": "late diagnosed autism adults",
156 "sources": ["reddit", "x", "youtube"],
157 "weight": 1.0,
158 }],
159 }
160 avail = ["reddit", "x", "youtube", "hackernews", "polymarket", "github"]
161 for depth in ("default", "deep"):
162 with self.subTest(depth=depth):
163 plan = planner._sanitize_plan(
164 raw,
165 "late diagnosed autism adults",
166 avail,
167 None,
168 depth,
169 honor_plan_sources=True,
170 )
171 self.assertEqual(["reddit", "x", "youtube"], plan.subqueries[0].sources)
172
173 def test_llm_plan_still_expands_narrow_sources_at_default_and_deep(self):
174 # Engine-internal LLM plans keep the expansion that lets fusion
175 # decide quality. Same snippet as #1073, without honor_plan_sources.
176 raw = {
177 "intent": "opinion",
178 "freshness_mode": "balanced_recent",
179 "cluster_mode": "debate",
180 "subqueries": [{
181 "label": "primary",
182 "search_query": "late diagnosed autism adults",
183 "ranking_query": "late diagnosed autism adults",
184 "sources": ["reddit", "x", "youtube"],
185 "weight": 1.0,
186 }],
187 }
188 avail = ["reddit", "x", "youtube", "hackernews", "polymarket", "github"]
189 for depth in ("default", "deep"):
190 with self.subTest(depth=depth):
191 plan = planner._sanitize_plan(
192 raw,
193 "late diagnosed autism adults",
194 avail,
195 None,
196 depth,
197 )
198 self.assertEqual(avail, plan.subqueries[0].sources)
199
200 def test_operator_plan_preserves_distinct_per_subquery_source_lists(self):
201 raw = {
202 "intent": "breaking_news",
203 "freshness_mode": "strict_recent",
204 "cluster_mode": "story",
205 "subqueries": [
206 {
207 "label": "primary",
208 "search_query": "kanye west",
209 "ranking_query": "What happened with Kanye West?",
210 "sources": ["reddit", "x", "youtube"],
211 "weight": 1.0,
212 },
213 {
214 "label": "album",
215 "search_query": "kanye west bully album",
216 "ranking_query": "How was Kanye West's BULLY album received?",
217 "sources": ["youtube", "reddit"],
218 "weight": 0.8,
219 },
220 ],
221 }
222 avail = ["reddit", "x", "youtube", "hackernews", "polymarket", "github"]
223 plan = planner._sanitize_plan(
224 raw,
225 "Kanye West",
226 avail,
227 None,
228 "default",
229 honor_plan_sources=True,
230 )
231 by_label = {sq.label: sq.sources for sq in plan.subqueries}
232 self.assertEqual(["reddit", "x", "youtube"], by_label["primary"])
233 self.assertEqual(["youtube", "reddit"], by_label["album"])
234
235 def test_quick_mode_prioritizes_explicit_requested_sources_within_cap(self):
236 raw = {
237 "intent": "product",
238 "freshness_mode": "balanced_recent",
239 "cluster_mode": "debate",
240 "subqueries": [
241 {
242 "label": "primary",
243 "search_query": "AI coding agents",
244 "ranking_query": "What are people saying about AI coding agents?",
245 "sources": ["reddit", "youtube", "grounding", "digg"],
246 "weight": 1.0,
247 }
248 ],
249 }
250 plan = planner._sanitize_plan(
251 raw,
252 "AI coding agents",
253 ["reddit", "youtube", "grounding", "digg"],
254 ["digg", "reddit", "youtube", "grounding"],
255 "quick",
256 )
257 self.assertIn("digg", plan.subqueries[0].sources)
258 self.assertLessEqual(len(plan.subqueries[0].sources), 2)
259
260 def test_quick_mode_preserves_explicit_requested_sources_in_fallback_plan(self):
261 plan = planner.plan_query(
262 topic="AI coding agents",
263 available_sources=["reddit", "youtube", "github"],
264 requested_sources=["reddit", "github"],
265 depth="quick",
266 provider=None,
267 model=None,
268 )
269 self.assertIn("github", plan.subqueries[0].sources)
270
271 def test_default_comparison_uses_all_capable_sources(self):
272 plan = planner.plan_query(
273 topic="codex vs claude code",
274 available_sources=["reddit", "x", "youtube", "hackernews", "polymarket"],
275 requested_sources=None,
276 depth="default",
277 provider=None,
278 model=None,
279 )
280 self.assertEqual("comparison", plan.intent)
281 for subquery in plan.subqueries:
282 # Default depth should not artificially cap sources
283 self.assertGreaterEqual(len(subquery.sources), 4)
284
285 def test_default_how_to_keeps_youtube_in_source_mix(self):
286 plan = planner.plan_query(
287 topic="how to deploy remotion animations for claude code",
288 available_sources=["reddit", "x", "youtube", "hackernews"],
289 requested_sources=None,
290 depth="default",
291 provider=None,
292 model=None,
293 )
294 self.assertEqual("how_to", plan.intent)
295 sources = plan.subqueries[0].sources
296 self.assertIn("youtube", sources)
297 self.assertIn("reddit", sources)
298
299 def test_how_to_sources_includes_capability_matched_extras(self):
300 """how_to routing should include additional sources beyond the core ones."""
301 plan = planner.plan_query(
302 topic="how to deploy on Fly.io",
303 available_sources=["reddit", "tiktok", "instagram", "youtube", "hackernews"],
304 requested_sources=None,
305 depth="default",
306 provider=None,
307 model=None,
308 )
309 self.assertEqual("how_to", plan.intent)
310 sources = plan.subqueries[0].sources
311 self.assertIn("youtube", sources)
312 self.assertIn("reddit", sources)
313 # Additional capability-matched sources should also be included
314 self.assertGreater(len(sources), 2,
315 f"how_to should include >2 sources, got {len(sources)}: {sources}")
316
317 def test_how_to_sources_includes_linkedin(self):
318 """LinkedIn has discussion capability and should be retained for how_to intent (#1543)."""
319 sources = planner._default_sources_for_intent(
320 "how_to", ["reddit", "linkedin", "x", "youtube", "hackernews"]
321 )
322 self.assertIn("linkedin", sources)
323
324 def test_ncaa_tournament_is_breaking_news(self):
325 intent = planner._infer_intent("NCAA tournament brackets")
326 self.assertEqual("breaking_news", intent)
327
328 def test_march_madness_is_breaking_news(self):
329 intent = planner._infer_intent("2026 March Madness")
330 self.assertEqual("breaking_news", intent)
331
332 def test_factual_plan_has_at_most_2_subqueries(self):
333 plan = planner.plan_query(
334 topic="who acquired Wiz",
335 available_sources=["reddit", "x", "hackernews"],
336 requested_sources=None,
337 depth="default",
338 provider=None,
339 model=None,
340 )
341 self.assertEqual("factual", plan.intent)
342 self.assertLessEqual(len(plan.subqueries), 2)
343
344 def test_default_how_to_prefers_longform_video_over_shortform(self):
345 plan = planner.plan_query(
346 topic="how to deploy on Fly.io",
347 available_sources=["reddit", "tiktok", "instagram", "youtube", "hackernews"],
348 requested_sources=None,
349 depth="default",
350 provider=None,
351 model=None,
352 )
353 self.assertEqual("how_to", plan.intent)
354 sources = plan.subqueries[0].sources
355 # how_to routing should include youtube (longform) over tiktok/instagram
356 self.assertIn("youtube", sources)
357 self.assertIn("reddit", sources)
358
359 def test_product_plan_can_include_jobs_source(self):
360 plan = planner.plan_query(
361 topic="Listen Labs features",
362 available_sources=["reddit", "youtube", "jobs", "hackernews"],
363 requested_sources=None,
364 depth="default",
365 provider=None,
366 model=None,
367 )
368 self.assertEqual("product", plan.intent)
369 self.assertIn("jobs", plan.subqueries[0].sources)
370 self.assertGreater(plan.source_weights["jobs"], plan.source_weights["youtube"])
371
372 def test_prediction_includes_tiktok_and_instagram(self):
373 """TikTok and Instagram are no longer excluded from prediction intent."""
374 plan = planner.plan_query(
375 topic="odds of US recession 2026",
376 available_sources=["reddit", "x", "tiktok", "instagram", "youtube", "hackernews", "polymarket"],
377 requested_sources=None,
378 depth="default",
379 provider=None,
380 model=None,
381 )
382 self.assertEqual("prediction", plan.intent)
383 all_sources = set()
384 for subquery in plan.subqueries:
385 all_sources.update(subquery.sources)
386 self.assertIn("tiktok", all_sources)
387 self.assertIn("instagram", all_sources)
388
389 def test_opinion_includes_tiktok_and_instagram(self):
390 """TikTok and Instagram are no longer excluded from opinion intent."""
391 plan = planner.plan_query(
392 topic="thoughts on OpenAI Codex pricing",
393 available_sources=["reddit", "x", "tiktok", "instagram", "youtube", "hackernews"],
394 requested_sources=None,
395 depth="default",
396 provider=None,
397 model=None,
398 )
399 self.assertEqual("opinion", plan.intent)
400 all_sources = set()
401 for subquery in plan.subqueries:
402 all_sources.update(subquery.sources)
403 self.assertIn("tiktok", all_sources)
404 self.assertIn("instagram", all_sources)
405
406 def test_comparison_includes_polymarket(self):
407 """Polymarket should not be excluded from comparison intent plans."""
408 plan = planner.plan_query(
409 topic="Sam Altman vs Dario Amodei",
410 available_sources=["reddit", "x", "youtube", "hackernews", "polymarket"],
411 requested_sources=None,
412 depth="default",
413 provider=None,
414 model=None,
415 )
416 self.assertEqual("comparison", plan.intent)
417 all_sources = set()
418 for subquery in plan.subqueries:
419 all_sources.update(subquery.sources)
420 self.assertIn("polymarket", all_sources)
421
422 def test_polymarket_excluded_from_how_to_and_concept(self):
423 """Polymarket should remain excluded from how_to and concept intents."""
424 for topic, expected_intent in [
425 ("how to deploy on Fly.io", "how_to"),
426 ("explain transformer architecture", "concept"),
427 ]:
428 plan = planner.plan_query(
429 topic=topic,
430 available_sources=["reddit", "x", "youtube", "hackernews", "polymarket"],
431 requested_sources=None,
432 depth="default",
433 provider=None,
434 model=None,
435 )
436 self.assertEqual(expected_intent, plan.intent)
437 all_sources = set()
438 for subquery in plan.subqueries:
439 all_sources.update(subquery.sources)
440 self.assertNotIn("polymarket", all_sources,
441 f"polymarket should be excluded from {expected_intent}")
442
443 def test_explicit_requested_sources_survive_intent_routing(self):
444 """--search sources are a user override at default/deep depth too."""
445 for topic, requested, expected_intent in [
446 ("will the fed cut rates in december", ["hackernews", "polymarket"], "concept"),
447 ("how to deploy on Fly.io", ["reddit", "youtube", "polymarket", "stocktwits"], "how_to"),
448 ]:
449 for depth in ("default", "deep"):
450 with self.subTest(topic=topic, depth=depth):
451 plan = planner.plan_query(
452 topic=topic,
453 available_sources=requested,
454 requested_sources=requested,
455 depth=depth,
456 provider=None,
457 model=None,
458 )
459 self.assertEqual(expected_intent, plan.intent)
460 all_sources = set()
461 for subquery in plan.subqueries:
462 all_sources.update(subquery.sources)
463 self.assertEqual(set(requested), all_sources)
464
465 def test_opinion_includes_polymarket(self):
466 """Polymarket should not be excluded from opinion intent plans."""
467 plan = planner.plan_query(
468 topic="thoughts on OpenAI future",
469 available_sources=["reddit", "x", "youtube", "hackernews", "polymarket"],
470 requested_sources=None,
471 depth="default",
472 provider=None,
473 model=None,
474 )
475 self.assertEqual("opinion", plan.intent)
476 all_sources = set()
477 for subquery in plan.subqueries:
478 all_sources.update(subquery.sources)
479 self.assertIn("polymarket", all_sources)
480
481 def test_breaking_news_includes_tiktok_and_instagram(self):
482 plan = planner.plan_query(
483 topic="2026 March Madness",
484 available_sources=["reddit", "x", "tiktok", "instagram", "youtube", "hackernews"],
485 requested_sources=None,
486 depth="default",
487 provider=None,
488 model=None,
489 )
490 self.assertEqual("breaking_news", plan.intent)
491 all_sources = set()
492 for subquery in plan.subqueries:
493 all_sources.update(subquery.sources)
494 self.assertIn("tiktok", all_sources)
495 self.assertIn("instagram", all_sources)
496
497
498 class IntentModifierBreadthTests(unittest.TestCase):
499 """Unit 2: Topics with intent modifiers (use cases, workflows, examples,
500 review, comparison) must fan out across paraphrased subqueries rather
501 than echo the literal phrase. 2026-04-19 Hermes Agent Use Cases failure.
502 """
503
504 def test_max_subqueries_raised_to_5_for_how_to(self):
505 self.assertEqual(5, planner._max_subqueries("how_to"))
506
507 def test_max_subqueries_raised_to_5_for_opinion(self):
508 self.assertEqual(5, planner._max_subqueries("opinion"))
509
510 def test_max_subqueries_raised_to_5_for_product(self):
511 self.assertEqual(5, planner._max_subqueries("product"))
512
513 def test_max_subqueries_unchanged_for_comparison(self):
514 from lib import competitors
515 self.assertEqual(
516 competitors.COMPARISON_ENTITY_MAX + 1,
517 planner._max_subqueries("comparison"),
518 )
519
520 def test_max_subqueries_unchanged_for_factual_and_concept(self):
521 self.assertEqual(2, planner._max_subqueries("factual"))
522 self.assertEqual(2, planner._max_subqueries("concept"))
523
524 def test_has_intent_modifier_detects_use_cases(self):
525 self.assertTrue(planner._has_intent_modifier("Hermes Agent use cases"))
526 self.assertTrue(planner._has_intent_modifier("Hermes Agent Actual Use Cases"))
527
528 def test_has_intent_modifier_detects_workflows(self):
529 self.assertTrue(planner._has_intent_modifier("Claude Code workflows"))
530
531 def test_has_intent_modifier_detects_review_and_tutorial(self):
532 self.assertTrue(planner._has_intent_modifier("Ollama review"))
533 self.assertTrue(planner._has_intent_modifier("DSPy tutorial"))
534
535 def test_has_intent_modifier_false_for_bare_entity(self):
536 self.assertFalse(planner._has_intent_modifier("Kanye West"))
537 self.assertFalse(planner._has_intent_modifier("hermes agent"))
538
539 def test_fallback_fans_out_when_intent_modifier_present(self):
540 plan = planner.plan_query(
541 topic="Hermes Agent use cases",
542 available_sources=["reddit", "x", "youtube", "hackernews"],
543 requested_sources=None,
544 depth="default",
545 provider=None,
546 model=None,
547 )
548 # Expect at least 3 subqueries total (primary + fanout); cap is 5 for
549 # how_to/opinion/product/breaking_news. Label set should include at
550 # least one of the paraphrase labels.
551 labels = {sq.label for sq in plan.subqueries}
552 self.assertGreaterEqual(len(plan.subqueries), 3)
553 self.assertTrue(
554 labels & {"workflows", "production", "experience"},
555 f"Expected paraphrase labels in {labels}",
556 )
557
558 def test_fallback_does_not_fan_out_for_bare_entity(self):
559 plan = planner.plan_query(
560 topic="Kanye West",
561 available_sources=["reddit", "x", "grounding"],
562 requested_sources=None,
563 depth="default",
564 provider=None,
565 model=None,
566 )
567 # Bare entity without intent modifier should not trigger the paraphrase
568 # fanout (those labels are not in the plan).
569 labels = {sq.label for sq in plan.subqueries}
570 self.assertFalse(labels & {"workflows", "production", "experience"})
571
572 def test_prompt_includes_intent_modifier_rule(self):
573 prompt = planner._build_prompt(
574 topic="Hermes Agent use cases",
575 available_sources=["reddit", "x", "youtube"],
576 requested_sources=None,
577 depth="default",
578 )
579 self.assertIn("INTENT-MODIFIER HANDLING", prompt)
580 self.assertIn("use cases", prompt)
581 self.assertIn("STRIP that phrase", prompt)
582
583
584 class FallbackDefaultsTests(unittest.TestCase):
585 """Unit 3: Deterministic fallback defaults and keyword_query quoting.
586 2026-04-19 Hermes Agent Use Cases failure.
587 """
588
589 def test_unclassified_topic_defaults_to_concept_not_breaking_news(self):
590 # Prior default was "breaking_news" with strict_recent freshness,
591 # which biased against older relevant material on unfamiliar topics.
592 self.assertEqual("concept", planner._infer_intent("some unfamiliar topic"))
593 self.assertEqual("concept", planner._infer_intent("Hermes Agent"))
594
595 def test_recency_signals_still_break_out_to_breaking_news(self):
596 self.assertEqual("breaking_news", planner._infer_intent("trending AI tools"))
597 self.assertEqual("breaking_news", planner._infer_intent("what's happening today"))
598 self.assertEqual("breaking_news", planner._infer_intent("this week in AI"))
599
600 def test_specific_intents_still_classify_correctly(self):
601 # Regression: other regex branches still fire as before.
602 self.assertEqual("how_to", planner._infer_intent("how to deploy Docker"))
603 self.assertEqual("factual", planner._infer_intent("who acquired Wiz"))
604 self.assertEqual("opinion", planner._infer_intent("thoughts on OpenAI Codex"))
605 self.assertEqual("comparison", planner._infer_intent("Codex vs Claude Code"))
606
607 def test_keyword_query_quotes_only_title_cased_proper_nouns(self):
608 # "Hermes Agent" is a multi-word title-cased proper noun — keep quoted.
609 # "Use Cases" is also title-cased BUT we only quote the first 2
610 # title-cased compounds; the first extracted is "Hermes Agent".
611 search = planner._keyword_query("Hermes Agent use cases", "hermes agent")
612 self.assertIn('"Hermes Agent"', search)
613 # The old behavior quoted the entire typed topic; confirm it does not.
614 self.assertNotIn('"Hermes Agent Actual Use Cases"', search)
615
616 def test_keyword_query_does_not_quote_bare_lowercase_topic(self):
617 search = planner._keyword_query("kanye west bully", "kanye west bully")
618 # Lowercase topics have no title-cased compound to quote.
619 self.assertNotIn('"', search)
620
621 def test_fallback_logs_warning_when_no_provider(self):
622 import io
623 import contextlib
624 buf = io.StringIO()
625 with contextlib.redirect_stderr(buf):
626 planner.plan_query(
627 topic="Hermes Agent use cases",
628 available_sources=["reddit", "x"],
629 requested_sources=None,
630 depth="default",
631 provider=None,
632 model=None,
633 )
634 output = buf.getvalue()
635 # New language: "No --plan passed" + "YOU ARE the planner" +
636 # runtime enumeration. Unit 4 (2026-04-19) rewrite to stop the
637 # "no provider = no LLM = I need a key" misread.
638 self.assertIn("No --plan passed", output)
639 self.assertIn("YOU ARE the planner", output)
640 self.assertIn("you ARE the LLM", output)
641 # Runtime-agnostic: each supported runtime name should appear.
642 for runtime_name in ("Claude Code", "Codex", "Hermes", "Gemini"):
643 self.assertIn(runtime_name, output)
644 # The old misleading phrasing must NOT appear.
645 self.assertNotIn("No --plan and no LLM provider configured", output)
646
647 def test_provider_failure_logs_error_and_law7_reminder(self):
648 # When a provider is configured, the provider path runs; if it
649 # errors, we get the "LLM planning failed" message AND the
650 # "No --plan passed" guidance: a failed internal planner degrades
651 # the run exactly like having none, and the host may not be
652 # detectable (see test_law7_host_plan_gate.py).
653 import io
654 import contextlib
655 buf = io.StringIO()
656
657 class _NoopProvider:
658 def generate_json(self, model, prompt):
659 raise ValueError("force fallback for test")
660
661 with contextlib.redirect_stderr(buf):
662 planner.plan_query(
663 topic="Kanye West",
664 available_sources=["reddit", "x"],
665 requested_sources=None,
666 depth="default",
667 provider=_NoopProvider(),
668 model="some-model",
669 )
670 output = buf.getvalue()
671 self.assertIn("LLM planning failed", output)
672 self.assertIn("No --plan passed", output)
673
674
675 class EnablementIntentTests(unittest.TestCase):
676 """A hosted service report: "best Grok AI bot to control my
677 computer agent" was planned as a strict-recent comparison about Grok, so
678 retrieval never looked for the tools that give Grok that capability."""
679
680 TOPIC = "best Grok AI bot to control my computer agent"
681 SOURCES = ["reddit", "x", "youtube", "hackernews", "github"]
682
683 def _raw(self, intent="comparison", cluster_mode="debate"):
684 return {
685 "intent": intent,
686 "freshness_mode": "strict_recent",
687 "cluster_mode": cluster_mode,
688 "subqueries": [
689 {
690 "label": "primary",
691 "search_query": "Grok computer control",
692 "ranking_query": "How can Grok control my computer?",
693 "sources": ["reddit", "github"],
694 }
695 ],
696 }
697
698 def test_enablement_phrasing_infers_how_to(self):
699 for topic in (
700 self.TOPIC,
701 "best grok bot control my computer agent",
702 "get claude to control my browser",
703 "how to make chatgpt use my mac",
704 "agent that automates the desktop",
705 "let codex drive my desktop",
706 "get claude code to use my terminal",
707 ):
708 with self.subTest(topic=topic):
709 self.assertEqual("how_to", planner._infer_intent(topic))
710
711 def test_near_misses_keep_their_intent(self):
712 self.assertEqual("concept", planner._infer_intent("best wireless earbuds"))
713 for topic in (
714 "best browser for privacy",
715 "make sure I use the right charger",
716 "how to get users to use my app",
717 "should I let my kid use the phone",
718 "make kids use the computer less",
719 "AI drives the PC upgrade cycle",
720 ):
721 with self.subTest(topic=topic):
722 self.assertFalse(planner._is_enablement(topic))
723 self.assertEqual("comparison", planner._infer_intent("Grok vs Claude to control my computer"))
724
725 def test_ordinary_device_use_is_not_enablement(self):
726 for topic in (
727 "how to use my computer for video editing",
728 "how to use the browser devtools",
729 "Chrome uses the browser sandbox",
730 "teens use the phone too much",
731 ):
732 with self.subTest(topic=topic):
733 self.assertFalse(planner._is_enablement(topic))
734
735 def test_news_and_threats_are_not_enablement(self):
736 self.assertEqual(
737 "breaking_news", planner._infer_intent("latest news about malware controlling my browser")
738 )
739 for topic in (
740 "latest news about malware controlling my browser",
741 "is a hacker controlling my computer",
742 "someone is controlling my laptop remotely",
743 "Anthropic launched an agent that controls your computer",
744 ):
745 with self.subTest(topic=topic):
746 self.assertFalse(planner._is_enablement(topic))
747
748 def test_news_and_threat_words_outside_their_role_keep_enablement(self):
749 for topic in (
750 "get the latest Claude to control my browser",
751 "how to get the newly released Claude to use my mac",
752 "get claude to control my browser without malware",
753 "best AI agent to control my computer safely from hackers",
754 ):
755 with self.subTest(topic=topic):
756 self.assertEqual("how_to", planner._infer_intent(topic))
757
758 def test_llm_news_verdict_is_not_overridden(self):
759 topic = "latest news about malware controlling my browser"
760 plan = planner._sanitize_plan(
761 self._raw(intent="breaking_news", cluster_mode="story"), topic, self.SOURCES, None, "default"
762 )
763 self.assertEqual("breaking_news", plan.intent)
764 self.assertEqual("strict_recent", plan.freshness_mode)
765 self.assertEqual("story", plan.cluster_mode)
766
767 def test_llm_comparison_verdict_becomes_how_to(self):
768 plan = planner._sanitize_plan(self._raw(), self.TOPIC, self.SOURCES, None, "default")
769 self.assertEqual("how_to", plan.intent)
770 self.assertEqual("evergreen_ok", plan.freshness_mode)
771 self.assertEqual("workflow", plan.cluster_mode)
772
773 def test_explicit_plan_keeps_its_intent(self):
774 plan = planner._sanitize_plan(
775 self._raw(), self.TOPIC, self.SOURCES, None, "default", honor_plan_sources=True
776 )
777 self.assertEqual("comparison", plan.intent)
778 self.assertEqual("debate", plan.cluster_mode)
779
780 def test_explicit_comparison_is_not_overridden(self):
781 topic = "Grok vs Claude to control my computer"
782 plan = planner._sanitize_plan(self._raw(), topic, self.SOURCES, None, "default")
783 self.assertEqual("comparison", plan.intent)
784
785 def test_ordinary_topic_keeps_llm_intent(self):
786 plan = planner._sanitize_plan(
787 self._raw(intent="product", cluster_mode="none"), "best wireless earbuds", self.SOURCES, None, "default"
788 )
789 self.assertEqual("product", plan.intent)
790 self.assertEqual("none", plan.cluster_mode)
791
792 @staticmethod
793 def _searches(plan):
794 return [sq.search_query for sq in plan.subqueries]
795
796 def test_fallback_plan_searches_the_capability_without_the_host(self):
797 # The LLM planner can be down; the fallback still has to find general
798 # tools such as MCP servers that no post names beside the host.
799 plan = planner._fallback_plan(self.TOPIC, self.SOURCES, None, "default")
800 self.assertEqual("how_to", plan.intent)
801 self.assertEqual(
802 ["computer use MCP server", "desktop automation CLI for AI agents"],
803 self._searches(plan)[1:],
804 )
805
806 def test_fallback_capability_searches_follow_the_device(self):
807 plan = planner._fallback_plan("get claude to control my browser", self.SOURCES, None, "default")
808 self.assertIn("browser automation MCP server", self._searches(plan))
809
810 def test_fallback_adds_no_capability_search_to_other_topics(self):
811 for topic in ("best wireless earbuds", "how to use my computer for video editing"):
812 with self.subTest(topic=topic):
813 plan = planner._fallback_plan(topic, self.SOURCES, None, "default")
814 self.assertFalse(any("MCP" in search for search in self._searches(plan)))
815
816 def test_quick_fallback_keeps_one_search(self):
817 self.assertEqual(1, len(planner._fallback_plan(self.TOPIC, self.SOURCES, None, "quick").subqueries))
818
819 def test_llm_plan_without_a_capability_search_gets_one(self):
820 plan = planner._sanitize_plan(self._raw(), self.TOPIC, self.SOURCES, None, "default")
821 self.assertEqual(["Grok computer control", "computer use MCP server"], self._searches(plan))
822
823 def test_llm_plan_with_a_capability_search_is_left_alone(self):
824 raw = self._raw()
825 raw["subqueries"].append(
826 {"label": "tools", "search_query": "browser automation CLI agent", "ranking_query": "Which CLIs?"}
827 )
828 plan = planner._sanitize_plan(raw, self.TOPIC, self.SOURCES, None, "default")
829 self.assertEqual(["Grok computer control", "browser automation CLI agent"], self._searches(plan))
830
831 def test_llm_capability_search_naming_the_host_still_gets_a_host_free_one(self):
832 raw = self._raw()
833 raw["subqueries"][0]["search_query"] = "Grok MCP computer control"
834 plan = planner._sanitize_plan(raw, self.TOPIC, self.SOURCES, None, "default")
835 self.assertEqual(["Grok MCP computer control", "computer use MCP server"], self._searches(plan))
836 self.assertTrue(fusion.capability_labels(plan))
837
838 def test_explicit_plan_gets_no_capability_search(self):
839 plan = planner._sanitize_plan(
840 self._raw(), self.TOPIC, self.SOURCES, None, "default", honor_plan_sources=True
841 )
842 self.assertEqual(["Grok computer control"], self._searches(plan))
843
844
845 if __name__ == "__main__":
846 unittest.main()
847
847 lines PYTHON