# CTE plan generation technique (Agent View Generation) Adapted from the AV-SQL CTE step. CTEs incrementally capture the information needed to answer the rewritten question, WITHOUT answering the final question (that is the next phase). Rules (from the AV-SQL discipline, hold verbatim): 1. Copy table and column names EXACTLY from the schema context provided (`tht schema render --format mschema-text --table ...`). Never invent objects that are not present. 2. Always keep the keys (PK and join columns) in the CTEs: they will be needed later. 3. Better one column too many than one too few: if unsure, include it. 4. One CTE = one informative subset with a clear purpose (e.g. "ricoveri with ablazione in 2025"), named in a speaking snake_case. 5. CTEs can chain-reference each other; the last one in the file is the one that `tht cte test` will query. 6. Each file in `sessions//ctes/.sql` contains ONLY the `WITH ... AS (...)` block (multi-CTE allowed), WITHOUT a trailing SELECT. A `SELECT ...` line after the WITH block causes an error in `tht cte test`: never add it. CTEs are tested **and approved (decision `cte_approved`) in plan order**: the next CTE is testable ONLY after the previous one is approved with `kind:"cte_result"`. The CLI refuses out-of-order CTEs (exit 5). 7. Filters: use field values verified with `tht search` (LSH match on real values), not imagined values. Presentation to the reviewer, for each CTE in the plan: > **** — purpose: > Tables used: (all from the promoted perimeter) > ```sql > WITH AS (...) > ``` After confirmation (or for direct reviewer review) write the file and test: `tht cte test --session `. On error or relevant warnings, discuss the correction with the reviewer before rewriting the file. If the reviewer edits the file by hand, RE-READ it before re-testing.