AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(planner): reject invalid explicit plan schemas
spiky02plateau85143d3c4e39
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 528c3c84..2f5dc1f6 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -3160,6 +3160,12 @@ def _main(# and burning a paid run the user did not ask for. Mirrors the# --plan file-read branch above and parse_competitors_plan.raise SystemExit(2)+ from lib import planner as _plan_validator+ try:+ _plan_validator.validate_external_plan(external_plan)+ except ValueError as exc:+ sys.stderr.write(f"[Planner] Invalid --plan schema: {exc}.\n")+ raise SystemExit(2)# Auto-resolve: use web search to discover subreddits/handles before planning.# This is the engine-side equivalent of SKILL.md Steps 0.55/0.75 for platformsdiff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 9c933ad2..816fd1c1 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -1970,9 +1970,10 @@ def run(if hiring_signals_mode and not planner_requested_sources:planner_requested_sources = ["jobs"]- if external_plan:+ if external_plan is not None:# External plan provided (e.g., from Claude Code via --plan flag).- # Parse it through the same sanitizer to validate structure.+ # Explicit input is a contract: validate it before permissive sanitization.+ planner.validate_external_plan(external_plan)plan = planner._sanitize_plan(external_plan, topic, available, planner_requested_sources, depth,)diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.pyindex aa1d43c9..0137c3df 100644--- a/skills/last30days/scripts/lib/planner.py+++ b/skills/last30days/scripts/lib/planner.py@@ -93,6 +93,7 @@ ALLOWED_INTENTS = {"prediction",}ALLOWED_CLUSTER_MODES = {"none", "story", "workflow", "market", "debate"}+QUICK_SOURCE_PRIORITY = {"factual": ["hackernews", "reddit", "x", "xquik", "youtube"],"product": ["jobs", "youtube", "reddit", "x", "xquik", "tiktok"],@@ -156,6 +157,55 @@ SOURCE_CAPABILITIES = {"jobs": {"jobs", "company_signal", "link"},"corpus": {"reference", "analysis"},}+++def validate_external_plan(raw: dict) -> None:+ """Validate explicit-plan structure before permissive sanitization.++ Enum-like metadata stays permissive because direct pipeline callers rely on+ the sanitizer to canonicalize those values.+ """+ if not isinstance(raw, dict):+ raise ValueError("top-level plan must be an object")+ for field in ("intent", "freshness_mode", "cluster_mode", "subqueries"):+ if field not in raw:+ raise ValueError(f"missing required field '{field}'")+ for field in ("intent", "freshness_mode", "cluster_mode"):+ if not isinstance(raw[field], str) or not raw[field].strip():+ raise ValueError(f"field '{field}' must be a non-empty string")++ source_weights = raw.get("source_weights")+ if source_weights is not None and not isinstance(source_weights, dict):+ raise ValueError("field 'source_weights' must be an object when provided")+ for source, weight in (source_weights or {}).items():+ if (+ not isinstance(source, str)+ or not source.strip()+ or isinstance(weight, bool)+ or not isinstance(weight, (int, float))+ ):+ raise ValueError("field 'source_weights' must map source names to numbers")+ subqueries = raw["subqueries"]+ if not isinstance(subqueries, list) or not subqueries:+ raise ValueError("field 'subqueries' must be a non-empty array")+ for index, subquery in enumerate(subqueries):+ if not isinstance(subquery, dict):+ raise ValueError(f"subqueries[{index}] must be an object")+ for field in ("search_query", "ranking_query"):+ if not isinstance(subquery.get(field), str) or not subquery[field].strip():+ raise ValueError(f"subqueries[{index}].{field} must be a non-empty string")+ sources = subquery.get("sources")+ if not isinstance(sources, list) or not sources or not all(+ isinstance(source, str) and source.strip() for source in sources+ ):+ raise ValueError(f"subqueries[{index}].sources must be a non-empty string array")+ weight = subquery.get("weight")+ if weight is not None and (+ isinstance(weight, bool) or not isinstance(weight, (int, float))+ ):+ raise ValueError(f"subqueries[{index}].weight must be a number when provided")++DEFAULT_INTENT_CAPABILITIES = {"comparison": {"discussion", "video", "web", "reference", "social", "link", "market"},"how_to": {"discussion", "video", "web", "reference", "link"},diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.pyindex 43ccd19f..8477e29f 100644--- a/tests/test_cli_v3.py+++ b/tests/test_cli_v3.py@@ -90,6 +90,27 @@ class CliV3Tests(unittest.TestCase):self.assertEqual(2, result.returncode, result.stderr)self.assertIn("Invalid --plan JSON", result.stderr)+ def test_invalid_plan_structure_exits_nonzero_without_fallback(self):+ result = subprocess.run(+ [+ sys.executable,+ "skills/last30days/scripts/last30days.py",+ "test topic",+ "--mock",+ "--emit=json",+ "--plan",+ json.dumps({"queries": {"web": ["Berlin"]}}),+ ],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ encoding="utf-8",+ check=False,+ )+ self.assertEqual(2, result.returncode, result.stderr)+ self.assertIn("Invalid --plan schema", result.stderr)+ self.assertNotIn("fallback-plan", result.stderr)+def test_parse_search_flag_normalizes_aliases_and_dedupes(self):self.assertEqual(["grounding", "reddit", "hackernews"],diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.pyindex 0ef4f8cd..aa90a4ef 100644--- a/tests/test_pipeline_v3.py+++ b/tests/test_pipeline_v3.py@@ -54,6 +54,16 @@ class PipelineV3Tests(unittest.TestCase):self.assertIn("grounding", report.items_by_source)self.assertEqual("gemini", report.provider_runtime.reasoning_provider)+ def test_empty_explicit_plan_is_rejected(self):+ with self.assertRaisesRegex(ValueError, "intent"):+ pipeline.run(+ topic="test topic",+ config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},+ depth="quick",+ external_plan={},+ mock=True,+ )+def test_planner_trace_always_fires_on_mock_run(self):"""Unit 5: The unified planner trace emits one summary line plus oneline per subquery on every run, regardless of --debug. 2026-04-19diff --git a/tests/test_planner_v3.py b/tests/test_planner_v3.pyindex 64d55cf2..d1d37687 100644--- a/tests/test_planner_v3.py+++ b/tests/test_planner_v3.py@@ -4,6 +4,56 @@ from lib import plannerclass PlannerV3Tests(unittest.TestCase):+ def test_external_plan_rejects_valid_json_with_wrong_structure(self):+ with self.assertRaisesRegex(ValueError, "intent"):+ planner.validate_external_plan({"queries": {"web": ["Berlin"]}})++ def test_external_plan_accepts_documented_shape_without_source_weights(self):+ planner.validate_external_plan(+ {+ "intent": "breaking_news",+ "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "kanye west",+ "ranking_query": "What happened with Kanye West?",+ "sources": ["reddit", "x"],+ "weight": 1.0,+ }+ ],+ }+ )++ def test_external_plan_rejects_non_numeric_weight(self):+ base_plan = {+ "intent": "breaking_news",+ "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "kanye west",+ "ranking_query": "What happened with Kanye West?",+ "sources": ["reddit", "x"],+ "weight": 1.0,+ }+ ],+ }+ for invalid_weight in ("heavy", True):+ with self.subTest(subquery_weight=invalid_weight):+ invalid_plan = dict(base_plan)+ invalid_plan["subqueries"] = [+ dict(base_plan["subqueries"][0], weight=invalid_weight)+ ]+ with self.assertRaisesRegex(ValueError, "weight"):+ planner.validate_external_plan(invalid_plan)++ invalid_source_weight = dict(base_plan, source_weights={"x": True})+ with self.assertRaisesRegex(ValueError, "source_weights"):+ planner.validate_external_plan(invalid_source_weight)+def test_default_how_to_expands_past_llm_narrow_source_weights(self):raw = {"intent": "how_to",