refactor-model
Skill3 starsChanged 31 days agoMITView on GitHub
Refactors an existing analytical model while preserving its published output contract. Use when asked to simplify, reorganize, modularize, or improve model SQL without changing its grain, rows, columns, names, types, meanings, keys, or downstream behavior; use migration-plan instead when any contract change is intentional.
In this repository24 other files it gives its agents.
- analytics-requirementsSkill
- api-pipelineSkill
- bi-modelSkill
- build-modelSkill
- data-model-reviewSkill
- data-profileSkill
- data-quality-investigationSkill
- dbt-healthSkill
- explain-data-codeSkill
- freshness-investigationSkill
- incremental-modelSkill
- metric-definitionSkill
- migration-planSkill
- model-documentationSkill
- model-testsSkill
- project-profileSkill
- pr-reviewSkill
- rename-modelSkill
- semantic-layerSkill
- source-setupSkill
- sql-reviewSkill
- trace-lineageSkill
- validate-dbtSkill
- yaml-maintenanceSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 10 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 22
Do not use for model renames, intentional schema changes, or migrations.
- Very specific: line 26
Read .ae/exercise.json when present and honor its mode and constraints.
- Distinctive: line 33
Read the complete model, its configuration, documentation, tests, macros, direct inputs, and relevant project configuration.
- Distinctive: line 61
Every actionable finding includes severity and confidence plus Evidence, Risk, Recommendation, and Verification.
- Very specific: line 78
When contract preservation is uncertain or the work crosses a rename, deletion, or scope boundary, return # Refactor Proposal instead with: …
- Very specific: line 80
After an approved implementation, return # Refactor Result with: Files changed.
- Very specific: line 82
If evidence shows a contract change, return # Not a Refactor and identify the changed invariant plus the appropriate rename or migration …
- Distinctive: line 87
Check that references, selected columns, tests, and configurations still resolve locally.
- Distinctive: line 88
Prefer existing fixtures, compiled artifacts, or saved bounded outputs when already present.
- Distinctive: line 90
Never claim data equivalence without result evidence.
- Distinctive: line 95
Never call MCP, execute dbt, query a warehouse, or run pipelines.
- Distinctive: line 96
Never expose credentials, connection strings, PII, or unnecessary row-level values.
- Distinctive: line 97
Never execute mutating SQL or destructive version-control commands.
- Distinctive: line 103
Do not assume undocumented keys are unique, tests fully define the contract, output order is irrelevant, downstream searches cover …
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- Generated by scripts/build_targets.py from src/skills. Edit the source and rebuild; changes made here are overwritten. -->Self-contained install.
<skill-dir>is the directory holding this file: substitute its absolute path in the commands below and run them from the repository root. Read<skill-dir>/references/operating-rules.mdbefore acting; it holds the toolkit's always-on rules, which this install cannot load on its own. This install has no safety hooks, so the approvals those rules describe rest on you and the agent rather than on an enforced gate.
Refactor Model
Improve an analytical model's implementation without changing what consumers receive.
First check: the model's physical configuration
Before rewriting, list every key in the model's config() block and, for each, what the folder's dbt_project.yml entry sets for it. A key the folder does not set to the same value (partitioning, clustering, a required partition filter, sort or distribution keys, file format) is part of the output contract: it defines the physical table and what queries against it must supply. Those keys stay in the rewritten model, including when the request asks to drop or trim the block because the folder "already" covers it. Only keys the folder sets identically may go.
When to use
- Simplify CTEs, joins, filters, calculations, or repeated SQL in an existing model.
- Extract reusable logic or align a model with demonstrated repository conventions.
- Review whether a proposed refactor preserves the output contract.
- Do not use for model renames, intentional schema changes, or migrations.
Mode and context
Read .ae/exercise.json when present and honor its mode and constraints. Otherwise default silently to Work. In Learn mode, use progressive hints. In Assessment mode, evaluate the submission without editing it or supplying a replacement.
Obtain the target model, requested improvement, project root, and any declared compatibility constraints. Treat missing business meaning, grain, or consumer guarantees as unknowns rather than inventing them.
Procedure
- Establish repository conventions first. Read
.ae/project.ymlwhen present; otherwise runpython3 "<skill-dir>/scripts/infer_conventions.py" <project-root> --json. Record the adapter, transformation tool, model layout, SQL style, tests, and materialization patterns with their evidence strength. - Read the complete model, its configuration, documentation, tests, macros, direct inputs, and relevant project configuration.
- Define the current output contract from evidence:
- row population and grain;
- column names, order when contractually relevant, types, nullability, and meanings;
- keys, accepted values, time semantics, units, and materialization behavior;
- freshness, performance, and side effects only when documented or tested.
- Trace downstream lineage across models, tests, exposures, metrics, semantic definitions, BI artifacts, and orchestration references. List searched locations and exclusions.
- Compare the proposed implementation with the current one through each CTE. Check joins, fanout, filters, three-valued logic, aggregations, windows, deduplication order, casts, time zones, and incremental boundaries.
- Reject the refactor framing if preserving the contract is impossible. Route a name-only change to
rename-modeland an intentional contract change tomigration-plan. - Design the smallest change that removes the identified complexity while preserving every established invariant. Use only constructs and macros supported by repository and adapter evidence.
- When the user explicitly requested this contract-preserving refactor, apply the smallest reversible edits without asking for a second approval and show the resulting diff. If contract preservation is uncertain, the scope expands, or a rename/deletion is needed, preview the change and blast radius and obtain approval first. When the request adds a rename or removal of a published field to the refactor, apply the refactor with that field under its current name and ask about the rename separately, so the approved work is not held up by the part that needs approval.
- Change only files required by the request. New additive files may be created, but list every path.
- Re-read the before and after logic against every invariant and report anything that remains unverified.
Preservation checks
- The same logical input produces the same row set at the same grain.
- Joins retain the same cardinality and unmatched-row behavior.
- Filters retain boundaries, null behavior, and time anchors.
- Aggregations, windows, ties, and deduplication remain deterministic.
- Columns retain names, meanings, types, nullability, units, and defaults.
- Materialization, hooks, grants, tags, contracts, and incremental state retain behavior.
- Physical configuration carries over unchanged:
partition_by,cluster_by, sort and distribution keys, file format, and every other key in the originalconfig()block. When logic moves into new upstream models, the published model keeps its config block; adapter functions such assafe_dividestay unless the request is to port the model. A request to drop or trim the block because the folder already sets a default does not change this when the block sets anything the folder'sdbt_project.ymlentry does not: those keys define the physical table (partitioning, clustering, a required partition filter) and what queries against it must supply. Compare key by key, remove only keys the folder sets to the same value, keep the rest, and say which you kept and why.
Evidence required
Cite files and exact expressions for the current contract, each downstream dependency, and every proposed equivalence. Label facts as Observed, consequences as Inferred, and runtime questions as Unknown.
Every actionable finding includes severity and confidence plus Evidence, Risk, Recommendation, and Verification. Use the repository severity model and avoid presenting stylistic preference as a defect.
Failure modes
- Calling changed rows, grain, schema, meaning, or materialization a refactor.
- Optimizing a fragment without reading the whole model and direct dependencies.
- Assuming algebraically similar SQL has identical null, duplicate, or time behavior.
- Removing a column because no SQL model references it while ignoring BI consumers.
- Introducing an adapter-specific function absent from the repository.
- Dropping the original
config()block, or rewriting warehouse-specific SQL because the request said not to run against the warehouse. "No BigQuery" forbids execution, not the dialect. The same holds when the request asks to drop the block on the premise that the folder default covers it, without checking that premise key by key. - Editing outside the explicit request or changing an uncertain contract without approval.
- Claiming equivalence from compilation or formatting alone.
Output contract
For an explicitly requested contract-preserving refactor, return # Refactor with: Changed, followed by a before-and-after lineage diagram when the refactor adds, removes, or moves a layer: one mermaid block that opens flowchart TB, holds subgraph before then subgraph after, each starting direction LR, and ends with before ~~~ after so the old chain sits above the new one (details in <skill-dir>/references/diagrams.md); Why, including the preservation argument; Configuration, naming each original config() key as kept or removed and, for a removed key, the dbt_project.yml line that sets the same value; Verified; Remaining uncertainty.
When contract preservation is uncertain or the work crosses a rename, deletion, or scope boundary, return # Refactor Proposal instead with: Goal; Current output contract; Downstream blast radius; Proposed diff; Failure risks; Verification plan; Approval needed.
After an approved implementation, return # Refactor Result with: Files changed; Contract preserved; Evidence; Verification performed; Residual uncertainty; Follow-up commands not run.
If evidence shows a contract change, return # Not a Refactor and identify the changed invariant plus the appropriate rename or migration workflow.
Verification
- Perform static before/after tracing for grain, row population, columns, and semantics.
- Check that references, selected columns, tests, and configurations still resolve locally.
- Prefer existing fixtures, compiled artifacts, or saved bounded outputs when already present.
- Propose the smallest targeted compile, build, or equivalence checks, but do not execute them.
- Never claim data equivalence without result evidence; state the exact runtime check needed.
Safety
- Local-only: use repository files, local static tools, and existing artifacts.
- Never call MCP, execute dbt, query a warehouse, or run pipelines.
- Never expose credentials, connection strings, PII, or unnecessary row-level values.
- Never execute mutating SQL or destructive version-control commands.
- New files may be created without approval and every path must be reported.
- Explicitly requested reversible refactor edits may proceed after contract preservation is established. Renames, deletions, uncertain contracts, and scope expansion require preview, blast-radius disclosure, and approval.
What not to assume
Do not assume undocumented keys are unique, tests fully define the contract, output order is irrelevant, downstream searches cover proprietary BI formats, materialization changes are harmless, or matching column names imply matching meaning.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

