Sub topic 12
Combining the agent with codemods and structural search
This chapter assumes you can run a test suite and a linter, use Git branches and commits, and have already scoped a task with the agent. It also assumes you have seen the "small, reversible steps" and "verification loop" ideas from earlier chapters. Here you will learn when to hand a repetitive change to a deterministic tool and use the agent to direct that tool.
Why not let the agent edit every file?
A coding agent edits files one at a time. For a change that touches 300 call sites, that approach has three problems:
- Cost and time. Each file means reading, editing, and often a test run.
- Inconsistency. A language model can treat the 40th occurrence differently from the 3rd. It may skip one, reformat another, or "improve" a third.
- Review burden. You cannot tell whether a 300-file diff is uniform or has quiet exceptions.
A deterministic tool has the opposite profile. A codemod is a program that rewrites source code by rules. It applies one rule the same way everywhere and can be rerun. It has no judgment, so it will not notice the one call site that needs special handling.
The agent is good at the parts a codemod is bad at: reading the codebase, finding the pattern, writing the rule, and handling the leftovers. The split looks like this.
| Task | Better handled by |
|---|---|
| Rename a function at every call site | Codemod |
| Change argument order in a uniform way | Codemod |
| Decide which of three call styles apply to a file | Agent |
| Write the codemod rule and test it on examples | Agent |
| Fix the five call sites the rule cannot express | Agent |
| Update documentation prose around the change | Agent |
Text search versus structural search
Plain text search, such as grep or find-and-replace, matches characters. It does not know about code structure. A search for getUser( also matches comments, strings, and forgetUser(. A regular expression that handles nested parentheses in arguments becomes hard to write and hard to trust.
Structural search matches the syntax tree of the code. A syntax tree (or AST, abstract syntax tree) is the parsed form of a program: calls, arguments, and expressions as nodes. A structural tool such as ast-grep lets you write a pattern in the target language. Some parts of the pattern are placeholders:
$NAMEmatches one syntax node, such as a single argument.$$$ARGSmatches zero or more nodes, such as a whole argument list.
Because matching works on the tree, getUser(a, fn(b, c)) matches as a single call with two arguments. Comments and string contents are not matched. Line breaks and spacing do not matter.
A mechanical rename with ast-grep
Suppose a service renamed getUser to fetchUser, and the arguments stay the same. Run the search first, with no rewrite. This shows what the pattern matches.
ast-grep run --pattern 'getUser($$$ARGS)' --lang ts src/Then add --rewrite to see the proposed changes as a diff, and apply them only after you have looked.
ast-grep run --pattern 'getUser($$$ARGS)' --rewrite 'fetchUser($$$ARGS)' --lang ts src/
# review the proposed rewrites, then apply them
ast-grep run --pattern 'getUser($$$ARGS)' --rewrite 'fetchUser($$$ARGS)' --lang ts --update-all src/The first command only prints suggestions. The second writes files. Ask the agent to run the preview first and show you the match count before it applies anything. You can write that into the task description:
Rename getUser to fetchUser in src/ using ast-grep, not by editing files by hand.
Steps:
1. Run the pattern without --rewrite and report how many matches it finds.
2. Run it with --rewrite as a preview and show me three sample changes.
3. Wait for my approval, then apply with --update-all.
4. Run `npx tsc --noEmit` and `npm test`, and report both results.
5. List any remaining occurrences of getUser the pattern did not match.Step 5 matters. It makes the agent find the places the tool missed, which is where the agent's judgment is useful.
Saving a rule as a file
A command-line pattern is fine for one-off work. For a migration that spans several sessions or several developers, save the rule in a file so it is versioned and reviewable. In ast-grep, a rule is a YAML file.
# rules/get-user-to-fetch-user.yml
id: get-user-to-fetch-user
language: TypeScript
rule:
pattern: getUser($$$ARGS)
fix: fetchUser($$$ARGS)Run it as a scan:
ast-grep scan --rule rules/get-user-to-fetch-user.yml src/
ast-grep scan --rule rules/get-user-to-fetch-user.yml --update-all src/Commit the rule file on its own, before the rewrite it produces. A reviewer can then read a five-line rule and a mechanical diff. They do not have to read 300 edited call sites as if each were hand-written.
How the pieces fit together
The loop between the rule and the preview is cheap, because nothing is written to disk. Do your iteration there, not after the rewrite.
Gotchas
A pattern is narrower than you expect. getUser($$$ARGS) matches a bare call. It does not match api.getUser(id), which is a method call. It also does not match the name inside import { getUser } from "./users" or the function definition itself. To cover method calls, add a second pattern such as $OBJ.getUser($$$ARGS) with its own fix. Handle imports and definitions separately. A rename done with a codemod that skips the definition will compile in neither the old nor the new form.
A pattern is also wider than you expect. If two unrelated modules each export a function named getUser, the pattern renames calls to both. Structural search matches syntax, not meaning. It does not know which getUser a call resolves to. Narrow the search to the right directory, or add a constraint to the rule.
The tool does not understand your semantics. Changing getUser(id) to fetchUser(id) is safe if the new function takes the same arguments. If fetchUser returns a promise and getUser did not, every caller now needs await. A rename codemod makes the code look migrated while it is wrong. The type checker will catch some of this, and characterization tests will catch more.
Language support differs. ast-grep parses many languages, but the --lang value must match the files. For Python, libraries like LibCST offer a similar "parse, transform, print" approach. Java and Kotlin projects often use OpenRewrite. For a one-off, the agent can also write a throwaway script, but then you must review the script as well as its output.
Formatting can add noise. A rewrite may leave code in a style your formatter would change. Run the formatter in the same commit as the rewrite so later diffs stay small. Do not mix formatter output with hand edits.
Verifying a codemod run
Use the same checks you would use for any agent change, plus two specific to mechanical rewrites.
- Count matches before and after. If the preview reported 312 matches,
git diff --statshould show changes consistent with 312 edits. - Search for the old pattern again. The remaining matches are your list of leftovers.
- Read a sample of the diff rather than all of it. Because the change is uniform, a few hundred lines reviewed carefully tell you about the rest. Pay most attention to unusual files: generated code, test fixtures, and vendored directories that you did not mean to touch.
- Run the tests, type checker, and linter, as in earlier chapters.
git switch -c refactor/rename-get-user
git add rules/ && git commit -m "Add ast-grep rule for getUser rename"
ast-grep scan --rule rules/get-user-to-fetch-user.yml --update-all src/
git diff --stat
npx tsc --noEmit && npm test
ast-grep run --pattern 'getUser($$$ARGS)' --lang ts src/The last command should print nothing if the rename is complete. If it prints matches, they are the cases for the agent to handle by hand, each with its own small commit.
Choosing between the agent and a codemod
Use a codemod when the change can be described as "find this shape, replace with that shape" and you expect more than a few dozen sites. Use direct agent edits when each site needs a decision, or when there are only a handful. Use both when most sites are uniform and a few are not. In that case the codemod does the bulk, and the agent handles the exceptions under review.
The cost of a codemod is the time to write and test the rule. Below roughly ten call sites, that cost usually exceeds the benefit.
Exercise
You ask the agent to rename getUser to fetchUser with the rule getUser($$$ARGS). The preview shows 120 matches, and you apply it. Afterward, the tests pass, but a search finds 15 remaining uses of getUser in src/. Give two likely reasons the rule missed them, and say how you would handle them.
Show answer
Likely reasons: (1) The 15 uses are method calls such as api.getUser(id), which the bare-call pattern does not match. (2) They are imports, re-exports, or the function definition, where getUser is an identifier and not a call. For the first case, add a second pattern such as $OBJ.getUser($$$ARGS) with a matching fix, and preview it before applying. For the second, edit the imports and definition separately, either with another rule or by hand. Commit each fix on its own, then rerun the search, type checker, and tests.