Guardrail your agents with custom linters
Enforce codebase conventions and guardrail your coding agents with linters like ast-grep.
I have always cared about the quality of the software I deliver, and while I don't think everything has to be perfect I still strive for excellency and correctness. Today most of the code I deliver isn't written by hand, it's written by [current favorite harness], which right now is Claude Code. I think language models are excellent at solving business problems1, but I find they often try too clever or intricate approaches to a problem. The quality of their work has a lot of variance. It is thus my job to ensure that the agent's output is something I can take be held accountable for.
ast-grep is one of the tools I've found nice for making Claude not do stupid things, and as an added bonus it also helps humans on my team too.
Syntax-based linting
Let me first state that syntax-based linting is nothing new. Matter of fact it is how most linters work. The program parses your source code into an abstract syntax tree which is a directional acyclic graph representation of your program. Linters consist of rules that perform pattern matches on this graph to find redundant, unsafe, or non-compliant code.
Now tools like ast-grep allow you to define your own custom rules that match on the syntax trees. This means you can write tailored linting rules to your teams conventions and standards.
I think I should also note that ast-grep isn't the only tool in this space either. Some alternatives include Semgrep and GritQL, which solve similar problems. I don't have strong reasons to prefer ast-grep, but to me Semgrep tries to sell itself as an enterprise platform which I couldn't care for. GritQL doesn't have LSP support which is why I prefer ast-grep.
Generally speaking the tools have very similar capabilities.
- You can write your own rules, in ast-grep this is using a YAML format.
- When matching on a pattern, you can have the tool perform transforms to automatically fix the findings.
- To build confidence in your rules you can add snapshot tests.
- And you can always add more programming languages or even custom languages as long as they have a tree-sitter grammar available (or you can write your own).
This means you can build complex, in-house linting rules across all languages in your codebases that are enforced in your pre-merge checks. ast-grep's language-server (LSP) support enables both your editor and your agent harness discover the errors and are able to auto-fix them. Your rules can also formulate detailed error messages so your agent harness receives enough context on why the piece of code is problematic and how it can fix it.
Restricting developers and agents from harmful patterns
One of the codebases I work on has the entire SQL layer written in Python using the sqlalchemy library. SQLAlchemy has an unfortunate design choice which allows you to "commit" a transaction multiple times. Here is what it looks like...
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from sqlalchemy import text
async def foo(handle: async_sessionmaker):
async with handle() as db:
await db.execute(text("INSERT INTO users (id, name) VALUES (1, 'ast-grep')"))
await db.commit()
await db.execute(text("UPDATE users SET name = 'semgrep' WHERE id = 1"))
await db.commit()
You are probably as confused as I was the first time I saw this. How can you commit a singular database transaction twice? Well the truth is: you can't. What actually happens here is that SQLAlchemy commits the original transaction after the first commit. Subsequent commands are then buffered, and a new transaction opens and commits on the second commit() call. The resulting SQL looks something like this:
BEGIN TRANSACTION t1;
INSERT INTO users (id, name) VALUES (1, 'ast-grep');
COMMIT TRANSACTION t1;
BEGIN TRANSACTION t2;
UPDATE users SET name = 'semgrep' WHERE id = 1;
COMMIT TRANSACTION t2;
So with this one single API SQLAlchemy makes it very easy to accidentally break transactional atomicity by accident. Once you are aware of this pitfall you can try to avoid it, but this codebase spans a few hundred thousand lines, substantial parts of it is older, and we've found multiple places where we commit transactions twice.
Let's add an ast-grep rule to detect this.
# .ast-grep/rules/no-double-commit.yaml
id: no-double-commit
language: python
severity: error
message: Session `$DB` is committed more than once.
rule:
pattern: await $DB.commit()
inside:
kind: expression_statement
follows:
stopBy: end
has:
pattern: await $DB.commit()
Running ast-grep will now flag the bad code from our example.
error[no-double-commit]: Session `db` is committed more than once.
┌─ example.py:9:7
│
7 │ await db.commit()
│ -----------------
8 │ await db.execute(text("UPDATE users SET name = 'semgrep' WHERE id = 1"))
9 │ await db.commit()
│ ^^^^^^^^^^^^^^^^^
Error: 1 error(s) found in code.
Help: Scan succeeded and found error level diagnostics in the codebase.
Matching on trees, especially syntax trees makes it surprisingly easy to flag code that doesn't break the rules. Often very similar code can have significantly different semantics. To avoid false positives and gain confidence in our rules we can write tests.
# .ast-grep/tests/no-double-commit.yaml
id: no-double-commit
valid:
- |
async def foo(handle):
async with handle() as db:
await db.execute(text("INSERT INTO users (id, name) VALUES (1, 'ast-grep')"))
await db.commit()
- |
async def foo(handle):
async with handle() as db:
await db.commit()
async with handle() as db:
await db.commit()
- |
async def foo(a, b):
await a.commit()
await b.commit()
invalid:
- |
async def foo(handle):
async with handle() as db:
await db.execute(text("INSERT INTO users (id, name) VALUES (1, 'ast-grep')"))
await db.commit()
await db.execute(text("UPDATE users SET name = 'semgrep' WHERE id = 1"))
await db.commit()
Now you can add a pre-merge check step to run ast-grep over the entire codebase and your rules will be enforced.
It's no silver bullet
I think ast-grep is a lovely tool, but as with any tool it has its limitations. Because the rules are entirely syntax-driven you have no semantic context. By that I mean there is no type information, and if your programming language allows for many ways to do the same thing you'll have to write pretty extensive rules. Depending on the programming language and tooling you work with, a linter specifically for your language (such as Biome2 in JavaScript) might have support for writing your own rules too. Specialized tools often offer more specialized features than generic ones, but that does not mean either becomes obsolete.
I think one of the biggest benefits of syntax-based linting is that it's fully independent of whatever tooling your codebases use. This makes it very easy to build comprehensive in-house rules that are applicable to most codebases within an organization. Polyglot language support also means you can run checks everywhere with a singular tool, which I personally think is very neat.
There is also naturally an additional maintenance burden of maintaining your own linter rules, as compared to builtin rules in other linters. I would also not consider ast-grep a replacement for any other linter. It is however, a great supplement. I personally run ast-grep along with Biome and Clippy on my own projects.
My experiences
Having used ast-grep for a while, I find that it's easier to write good guidelines and standards for what good and correct code looks at in our organization. I find it to be both useful to catch problematic code, but also to serve as documentation to why we prefer to do things in a certain way.
In my opinion, consistency (as in the code looks and feels consistent, not the distributed systems definition) is one of the most important traits of a codebase. You might deal with a lot of crap in large codebases, but I find it's generally easier to navigate and deliver features in codebases that look and feel consistent. If we can use tools to ensure code looks consistent, then that's something I will value highly.
It's also pretty easy to add more rules. You can just ask your agent and it's probably going to cook up something workable.
Footnotes
-
When I say that Claude is excellent at solving business problems I am primarily pointing towards language models being good at turning a sequence of steps into workable code. They are great for solving the problem, however, the problem is often solved in a way that doesn't respect established conventions or engineering practices. ↩
-
GritQL is actually made by the Biome developers, so Biome is very flexible. In any case, Biome also allows you to write JavaScript code to define rules too. Pretty cool and nice! ↩
Blog content licensed under CC BY-NC-SA 4.0 DEED. No language models were used in the creation of the content.