Skip to main content
Ai promptsAgent promptsCodemodRefactoring

Codemod Authoring Prompt: Turn a Before/After Into an AST Transform

A codemod authoring prompt turns one before/after example into a tested jscodeshift or ast-grep transform with an idempotency check. Copy the structure.

PPromptsCart Team·June 21, 2026·Updated June 21, 2026·7 min read

You can describe the refactor in one sentence: "rename this call, move the second argument into an options object." Doing it across 800 files by hand is a week of tedium and three subtle mistakes. A codemod authoring prompt turns the one example into the transform that does all 800, on the AST, with a guard so re-running it is safe.

Most people reach for find-and-replace or a regex. It works on the first ten files and breaks on the eleventh, where the call spans three lines or sits inside a string. Text matching doesn't understand code structure. A codemod does, because it operates on the syntax tree, but writing one means learning jscodeshift or ast-grep internals you'll forget by next quarter.

The prompt closes that gap. You supply a before and an after, and it writes the tree-aware transform so you don't have to memorize the visitor API.

Why a regex isn't a refactor

A regex matches characters. Code has structure the characters only hint at. The same function call can be formatted five ways, span multiple lines, or appear inside a template string where it shouldn't be touched at all. Regex can't tell the difference. An AST transform can, because it sees nodes, not text.

Here's the take. Hand-writing codemods is a skill worth not having. The jscodeshift API is fiddly, the ast-grep YAML is its own dialect, and you use them rarely enough to forget between jobs. Offloading the API to a prompt while you keep ownership of the before/after spec is the right division of labor. You know the transform you want. Let the prompt translate it into the tool's grammar.

What a codemod authoring prompt does

A codemod authoring prompt is a transform generator that reads one before/after example and outputs a runnable, idempotent codemod plus a dry-run review. It converts intent into a tree transform.

Use it to:

  • Turn a single before/after pair into a complete jscodeshift or ast-grep codemod
  • Generate the transform per language from the same spec
  • Produce a dry-run diff to inspect before any file changes
  • Bake an idempotency guard into the output so re-runs are safe
  • Flag edge cases the example didn't cover (nested calls, aliased imports)
  • Output a verification step that confirms the result post-apply

The idempotency guard is the part hand-rolled codemods usually forget.

Anatomy of the prompt

Variables
  {{before_example}}   → code as it looks today
  {{after_example}}    → code as it should look
  {{target_tool}}      → jscodeshift | ast-grep | etc.
  {{language}}         → the source language

Prompt
  Role: you are a codemod author.
  Task: write a {{target_tool}} codemod that transforms
        {{before_example}} into {{after_example}}.
  Rules:
    - Operate on the AST, never on raw text.
    - Skip nodes already in the target shape (idempotency).
    - Don't touch matching text inside strings or comments.

Output contract
  Return: codemod source + idempotency guard + dry-run notes.

1. Write the before and after

The whole transform is inferred from {{before_example}} and {{after_example}}. Make them representative. If your real code has the call inside a .then(), put one example there so the model doesn't assume top-level only.

2. Pick the tool

Set {{target_tool}}. jscodeshift for JS/TS ecosystems, ast-grep for a polyglot repo. The prompt adapts the output to the tool's grammar.

3. Review the dry run

Never apply blind. The output includes a dry-run section. Read the sample diffs and confirm the transform isn't catching nodes it shouldn't.

4. Apply with verification

Once the dry run looks right, apply and run the verification step the prompt emits. That's your confirmation the transform did what the example promised.

Make idempotency a hard rule

A codemod that isn't idempotent is a landmine. A partial run gets re-applied, and now you've double-transformed half the files. State the guard in the rules section: "before transforming a node, check whether it already matches the target shape; if so, skip it." Claude tends to add the guard when it's an explicit rule; without it, both Claude and GPT-4o write the happy-path transform and leave re-runs unsafe.

Prompt-craft patterns for codemods

Give a representative before, not the simplest one. A trivial example teaches the model a trivial transform. If the real code varies, show the variation, or the codemod handles the easy case and silently skips the rest.

Force a dry run before apply. A codemod that writes files on the first run gives you no chance to catch a bad match. Splitting generate, dry-run, and apply into separate steps is the safety margin.

Name the tool explicitly. "Write a codemod" without {{target_tool}} gets you pseudocode. jscodeshift and ast-grep have different mental models; the prompt needs to know which grammar to emit.

jscodeshift vs ast-grep, and how the model handles each

The tool you name changes what the prompt has to get right. jscodeshift gives you a full JavaScript visitor API, which is powerful and verbose. ast-grep uses a pattern-and-rewrite syntax that's terser but less expressive. Neither model writes both equally well.

Concernjscodeshiftast-grep
Output shapeA JS transform moduleA YAML rule with pattern and fix
Model reliabilityStrong on Claude and GPT-4o; both know the APILooser; the pattern syntax gets invented if the prompt doesn't pin it
Best forComplex JS/TS rewrites with logicFast, mostly-mechanical pattern swaps across languages
Idempotency guardAn explicit node check in the visitorA condition in the rule's constraints

The practical read: for a JS-only repo doing a non-trivial transform, ask for jscodeshift and let the model write real visitor logic. For a polyglot repo or a simple pattern swap, ast-grep is leaner, but you have to give the model an example of valid rule syntax or it'll guess. Pin the model version once a codemod reads correctly. A transform generator that drifted after a model update can produce subtly wrong AST traversals that pass the dry run on your example and fail on the file you didn't check. That's the failure that hurts at scale.

Variables you'll set

VariableRequiredWhat it is
{{before_example}}YesCode as it looks today
{{after_example}}YesCode as it should look
{{target_tool}}YesThe codemod tool to target
{{language}}RecommendedSource language for syntax rules

Getting started

  1. Copy the structure into your model.
  2. Fill {{before_example}} and {{after_example}} with a representative pair.
  3. Set {{target_tool}} to jscodeshift, ast-grep, or your tool of choice.
  4. Run it, then read the dry-run section before applying anything.
  5. Apply the codemod and run the verification step it returns.
  6. Re-run it once to confirm the idempotency guard holds.

To go from spec to applied transform with the dry-run and verify steps already wired together, the Codemod Authoring Harness handles the loop.

Browse the refactoring prompt packs
Skip the setup

The Codemod Authoring Harness does this end-to-end: a {{before_example}} and {{after_example}} pair feeds a codemod-generator prompt, a dry-run-review step shows sample diffs before a single file changes, and an apply-and-verify prompt confirms correctness after the transform runs. It's part of The Complete AI Prompts Bundle, a one-time lifetime license to the full catalog plus packs added later, sensible if you run more than the occasional large refactor.

Get the Codemod Authoring Harness

Codemods are one slice of large-scale refactoring. When the change crosses languages rather than rewriting one, the Cross-Language Refactor Harness preserves idioms the codemod can't reason about. Before applying any sweeping transform, the monorepo impact analysis prompt tells you which packages a change touches. For the build-versus-buy decision, see how to choose a reusable AI prompt pack.

See the impact-analysis pack
FAQ

Common questions

What is a codemod authoring prompt?
It's a structured prompt that takes a single before/after code example and outputs a runnable codemod (jscodeshift, ast-grep, or another AST tool) that applies the same transform across a codebase. It bakes an idempotency check into the output contract so re-running the codemod is safe.
Why use an AST codemod instead of find-and-replace?
Find-and-replace matches text, not structure, so it rewrites strings and comments it shouldn't and misses formatting variants. A codemod operates on the abstract syntax tree, so it only transforms real syntax nodes. The prompt's job is to turn your example into that tree-aware transform without you learning the AST API by hand.
How do you make a codemod idempotent?
Guard the transform so it skips nodes that already match the target shape. A codemod authoring prompt should output a precondition check: if the node is already transformed, leave it. That way running the codemod twice produces the same result as running it once, which matters when a partial run gets re-applied.
Stop reading. Start shipping.

Get the prompt packs this guide is built on

Ready-to-paste prompts with documented variables and worked examples for ChatGPT, Claude, and Gemini. One-time payment, own it forever.