"""cev L_plan Planner — design-time LLM that emits a validation_intent_battery. Spec: docs/build/B5_planner.md + docs/REBUILD_DESIGN.md §2 (decision A, iron-rules 1/2/3, §2.6 layering). Frozen contract: cev/schemas/validation_intent_battery.schema.json. Core principles carried over from validation_agent/core/planner.py, RESHAPED so the output is *validation intents only* — no tool_id / no params / no data_construction: - dataset-endogenous (iron-rule 1): plan only what feasibility + DataInventory support; - the LLM is the decider, ZERO rules (D2): deterministic code only assembles the prompt and validates output SHAPE — it never authors intents; - intents carry no tool / lib / params / data_construction (iron-rule 2); - no silent truncation (D7): everything unsupportable goes to not_planned + reason_code. This module is intentionally LIGHT: it consumes already-built dicts (edge / paper_context / feasibility / data_inventory / constraints) + an injected LLM provider, so it imports no pandas/pyarrow and is unit-testable with a fake provider. Heavy upstream loading lives in cev/cli.py. HPP runtime never runs this (design-time LLM only; hpp_llm_forbidden guard). """ from __future__ import annotations import json from pathlib import Path from typing import Any, Protocol _SCHEMA_PATH = ( Path(__file__).resolve().parent.parent / "schemas" / "validation_intent_battery.schema.json" ) DEFAULT_PLANNER_MODEL = "claude-opus-4-8" PLANNER_AGENT = "cev_planner" MAX_PLANNER_SCHEMA_REPAIRS = 2 _MAX_REPAIR_ERRORS = 10 # Mirrored from the frozen schema for convenience (the schema file is the authority). INTENT_TYPES = ( "correlation", "main_effect", "subgroup_cate", "dose_response", "mediation_nie_nde", "sensitivity", "negative_control", "iv_mr", "bidirectional", "alt_estimator", ) # tokens that must never appear in an intent (iron-rule 2 purity guard, B5 §3.4) _FORBIDDEN_TOKENS = ("tool_id", "data_construction", "value_filter", ".tmpl", "data_construction_spec") _INPUT_LABELS = ("edge", "paper_context", "feasibility", "data_inventory", "constraints") class PlannerError(RuntimeError): """A Planner failure carrying a stable B5 §8 failure code.""" def __init__(self, message: str, *, code: str) -> None: super().__init__(message) self.code = code class LLMProvider(Protocol): # structural; avoids importing the heavy provider module def call(self, *, agent: str, prompt: str, **kwargs: Any) -> dict[str, Any]: ... PLANNER_SYSTEM_PROMPT = """\ You are the design-time Planner (L_plan) of the cev causal-validation engine. For ONE causal edge, on the current synthetic dataset (HPP-isomorphic), design the MOST COMPREHENSIVE, medically-justified validation battery that THE DATA CAN ACTUALLY SUPPORT, and emit it as VALIDATION INTENTS ONLY. # YOU ARE THE DECIDER — ZERO RULES, ZERO TOOLS - Every decision (which mechanisms to probe, which intent_types, which subgroups / mediators / contrasts, how comprehensive to be) is YOURS. There is no rule table. - Do NOT name any tool, tool_id, statistical library, estimator implementation, template, or parameter. Do NOT emit data_construction, value_filter, cohort, joins, or per-SD scaling — those are decided by downstream layers, not you. - Express each verification as a validation_intent whose intent_type is from the FIXED enum. # OUTPUT — STRICT JSON, an object with EXACTLY these three keys and nothing else { "intents": [ validation_intent, ... ], "tier_index": { "T1": [int, ...], "T2": [...], ... up to "T7": [...] }, "not_planned": [ { "intent_type", "x", "y", "reason_code", "detail" }, ... ] } No markdown fences, no comments, no trailing commas, no ellipsis, no extra keys. The system fills edge_id / battery_id / planner_model / dataset_version / feasibility_ref — you OMIT them. tier_index values are integer indices into intents[]; membership is your decision and a tier may be absent. Everything you judge warranted but UNSUPPORTABLE goes in not_planned (never silently skip it). validation_intent = { "intent_type": one of [correlation, main_effect, subgroup_cate, dose_response, mediation_nie_nde, sensitivity, negative_control, iv_mr, bidirectional, alt_estimator], "x": , "y": , "m": , "subgroup": , "contrast_type": , "covariates": [], "rationale": } # DATASET-ENDOGENOUS (binding — iron-rule 1) You are given `feasibility` (per-edge runnability + inferred equation/estimator + role mappings) and `data_inventory` (measured fields, dtypes, cross-table joinability, subgroup availability, n). Plan ONLY within them — never your imagination. - An equation / estimator marked not runnable (e.g. instrumental-variable / MR with no genetic instrument): do NOT emit a runnable intent for it → not_planned (reason_code=equation_not_runnable). EXCEPTION — longitudinal: when `feasibility.longitudinal.status == "ok"`, a within-subject change / longitudinal dose_response IS runnable (estimator `feasibility.longitudinal.candidate_estimator`, e.g. e3_change / e3_lmm over `feasibility.longitudinal.timepoints`) — PLAN it (T5), do NOT mark equation_not_runnable. - A subgroup dimension absent in data_inventory: no subgroup_cate for it → not_planned (no_subgroup_support). - No mediator mapped (edge M empty): no mediation_nie_nde → not_planned (no_mediator_mapped). - X or Y with mapping status "missing": no runnable intent on that role → not_planned (x_not_mapped / y_not_mapped). - dose_response: a continuous-X shape is valid cross-sectionally; do NOT reflexively skip it. `data_inventory[].timepoints` lists the distinct research_stage values on each role table — when the X role reports ≥2 timepoints, multi-timepoint X IS available, so PLAN the longitudinal / within-subject change dose_response (T5). Reserve not_planned (single_timepoint_no_dose) ONLY when the X role table has <2 timepoints. - Any role resolving to an EXCLUDED, non-physiological source (medications / dietary / behavioral or self-reported): never plan it → not_planned (excluded_physiological_only). # SUBGROUPS ARE DATA-DRIVEN, NOT A FIXED CATALOG `data_inventory.subgroup_candidates` lists EVERY field across the cohort's tables that can form ≥2 viable strata (with stratum sizes) — discovered generically from the data, NOT a preset list. Propose subgroup_cate for ANY candidate that is a clinically plausible effect modifier of THIS X→Y relationship (e.g. menopausal status for a sex-linked or hormonal outcome, body-composition / adiposity strata, comorbidity or disease-severity status), reasoning from clinical knowledge. The legacy `subgroup_availability` (D01–D09) is only a small subset — do NOT limit yourself to it. Skip a candidate only when it is clinically implausible as a modifier, or is the exposure/outcome itself. # COMPREHENSIVENESS — attempt everything the mechanism warrants + label every gap Cover the tier battery the data supports: T1 main_effect (primary X→Y). T2 standard subgroups (subgroup_cate per supported effect-modifier; interaction-LRT intent). T3 paper-named subgroups (from the study cohort / paper text). T4 sensitivity (adjustment-set / robustness variants the data supports). T5 dose_response (continuous-X shape; AND when feasibility.longitudinal.status=="ok", the within-subject change / longitudinal dose_response over timepoints — plan it). T6 alt_estimator (same X→Y under a different estimator family). T7 negative_control + bidirectional (reverse Y→X) sanity checks. Cross-cutting (not tier-bound): mediation_nie_nde (needs m), correlation (association probe). "Comprehensive" = attempt everything warranted AND record what the data cannot support in not_planned — Nature-Medicine level is the target ceiling, not a per-edge guarantee. # PHYSIOLOGICAL-ONLY Consume only objective physiological indicators + demographics; never plan an intent whose role resolves to an excluded source. """ def build_planner_input( *, edge: dict[str, Any], paper_context: dict[str, Any], feasibility: dict[str, Any], data_inventory: dict[str, Any], constraints: dict[str, Any], ) -> dict[str, Any]: """Assemble the (deterministic, timestamp-free) L_plan prompt input. Mirrors the proven validation_agent input shape MINUS data_inspection and candidate_subgroups (those came from data_inspector / subgroup_expander, dropped: the new planner designs subgroups generically as zero-rule intents). """ return { "edge": edge, "paper_context": paper_context, "feasibility": feasibility, "data_inventory": data_inventory, "constraints": constraints, } def build_prompt(planner_input: dict[str, Any], *, repair_suffix: str = "") -> str: """Render SYSTEM + one