Our project instructions said "never query the database from a controller; use a repository". The AI coding agent read that file every session and still added a raw query to a controller about once a week, usually while fixing something else in a hurry. Human contributors did it too. Code review caught most cases, but not all, and reviewers resented being the enforcement mechanism for a rule that a computer could check.
So we wrote a script. Then another. We now have about a dozen small rule checks, each under a hundred lines, each enforcing one convention. They run in pre-commit and again in CI. This post shows how we write them in four languages, how they report errors so agents fix them correctly, and how we introduce a new rule into a codebase that already breaks it.
What deserves a script
A rule is a good candidate when it is:
Specific to your project. General language problems belong in a linter (see our post on linters as guardrails).
Mechanically checkable. "Controllers do not call
DB::" is. "Controllers are well designed" is not.Repeatedly violated. If a rule has been broken once in two years, a review comment is cheaper.
Our current list includes: no database access in HTTP handlers, status values come from enums not string literals, every user-facing string goes through the translation function, every locale file has the same keys, every migration has a down step, no new direct dependency without an entry in the dependency log.
Output format: written for whoever fixes it
Every script prints errors in the same shape:
app/Http/Controllers/OrderController.php:42: RULE-DB01 database call in controller; move the query to app/Repositories/OrderRepository.php
path:line: RULE-ID message with the fix. Editors and CI annotations understand path:line:, the rule ID lets you search the docs, and the message says what to do instead. That last part matters for AI agents: an error that names the fix is fixed correctly far more often than "violation found". Exit code 1 on any error, 0 otherwise.
Python: pattern rules over source files
Python is our default for text-level rules because it is installed everywhere and easy to read:
#!/usr/bin/env python3
"""RULE-DB01: no database access in HTTP controllers."""
import re
import sys
from pathlib import Path
PATTERN = re.compile(r"\bDB::|::query\(\)|->rawQuery\(|\bselectRaw\(")
ROOT = Path("app/Http/Controllers")
BASELINE = set(Path("tools/rules/baseline/db01.txt").read_text().split()) \
if Path("tools/rules/baseline/db01.txt").exists() else set()
def main(paths: list[str]) -> int:
files = [Path(p) for p in paths] if paths else ROOT.rglob("*.php")
errors = 0
for f in files:
if ROOT not in f.parents or str(f) in BASELINE:
continue
for n, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):
if line.lstrip().startswith(("//", "*")):
continue
if PATTERN.search(line):
print(f"{f}:{n}: RULE-DB01 database call in controller; move it to a repository class")
errors += 1
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
It accepts file paths as arguments (pre-commit passes the staged files) and falls back to scanning the whole directory (CI runs it that way). Regex rules have false positives; keep the pattern narrow and the exceptions explicit.
Go: a real analyzer with go/analysis
When the rule depends on code structure rather than text, use the language's own parser. Go's golang.org/x/tools/go/analysis framework gives you type-checked syntax trees and a ready-made command:
package main
import (
"go/ast"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/singlechecker"
)
var Analyzer = &analysis.Analyzer{
Name: "nosqlinhttp",
Doc: "RULE-DB01: reports database/sql calls in internal/http",
Run: run,
}
var sqlMethods = map[string]bool{"QueryContext": true, "ExecContext": true, "QueryRowContext": true}
func run(pass *analysis.Pass) (any, error) {
for _, f := range pass.Files {
if !strings.Contains(pass.Fset.File(f.Pos()).Name(), "/internal/http/") {
continue
}
ast.Inspect(f, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || !sqlMethods[sel.Sel.Name] {
return true
}
if t := pass.TypesInfo.TypeOf(sel.X); t != nil && strings.Contains(t.String(), "database/sql") {
pass.Reportf(call.Pos(), "RULE-DB01 SQL call %s in HTTP layer; move it to internal/store", sel.Sel.Name)
}
return true
})
}
return nil, nil
}
func main() { singlechecker.Main(Analyzer) }
go run ./tools/rules/nosqlinhttp ./...
The type check (TypeOf(sel.X) contains database/sql) is what a regex cannot do: a method called QueryContext on our own repository type is fine, the same name on *sql.DB is not. Output already uses the path:line:col: message format.
Rust: a structural check with only the standard library
Not every rule is about source code. This one checks that every migration has a matching down file, using no external crates so it builds instantly:
use std::{collections::BTreeSet, fs, process::ExitCode};
fn main() -> ExitCode {
let dir = "migrations";
let names: BTreeSet<String> = match fs::read_dir(dir) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().into_string().ok())
.collect(),
Err(err) => {
eprintln!("{dir}: RULE-MIG01 cannot read directory: {err}");
return ExitCode::FAILURE;
}
};
let mut errors = 0;
for up in names.iter().filter(|n| n.ends_with(".up.sql")) {
let down = up.replace(".up.sql", ".down.sql");
if !names.contains(&down) {
println!("{dir}/{up}:1: RULE-MIG01 missing {down}; add a down migration or a comment explaining why it is irreversible");
errors += 1;
}
}
if errors > 0 { ExitCode::FAILURE } else { ExitCode::SUCCESS }
}
We keep Rust rule tools in a small workspace crate under tools/rules/ and build them once in CI with caching. For rules about Rust code itself, Clippy lints usually exist already and are the better choice.
Node: cross-file consistency
The locale rule compares JSON files, which is natural in JavaScript:
#!/usr/bin/env node
// RULE-I18N02: every locale has exactly the keys of the reference locale.
import { readFileSync, readdirSync } from "node:fs";
const dir = "resources/lang";
const flatten = (obj, prefix = "") =>
Object.entries(obj).flatMap(([k, v]) =>
v && typeof v === "object" ? flatten(v, `${prefix}${k}.`) : [`${prefix}${k}`]);
const load = (f) => new Set(flatten(JSON.parse(readFileSync(`${dir}/${f}`, "utf8"))));
const reference = load("en.json");
let errors = 0;
for (const file of readdirSync(dir).filter((f) => f.endsWith(".json") && f !== "en.json")) {
const keys = load(file);
for (const k of reference) if (!keys.has(k)) {
console.log(`${dir}/${file}:1: RULE-I18N02 missing key "${k}"; add a translation or copy the English text and mark it for review`);
errors++;
}
for (const k of keys) if (!reference.has(k)) {
console.log(`${dir}/${file}:1: RULE-I18N02 extra key "${k}" not in en.json; remove it or add it to en.json`);
errors++;
}
}
process.exit(errors ? 1 : 0);
Wiring into pre-commit and CI
pre-commit's local repository type runs scripts that live in your repo:
repos:
- repo: local
hooks:
- id: rule-db01
name: "RULE-DB01 no DB access in controllers"
entry: python3 tools/rules/db01.py
language: system
files: ^app/Http/Controllers/.*\.php$
- id: rule-i18n02
name: "RULE-I18N02 locale keys match"
entry: node tools/rules/i18n02.mjs
language: system
files: ^resources/lang/.*\.json$
pass_filenames: false
- id: rule-mig01
name: "RULE-MIG01 down migrations"
entry: cargo run -q --manifest-path tools/rules/Cargo.toml --bin mig01
language: system
files: ^migrations/
pass_filenames: false
pass_filenames: false is for whole-directory rules. In CI we run pre-commit run --all-files, because local hooks can be skipped with git commit --no-verify and CI cannot. For AI agents, a hook that runs the same scripts after edits gives faster feedback than waiting for a commit.
Introducing a rule into existing code
A new rule that fails on three hundred existing lines will be disabled within a day. We use a baseline:
Run the rule, write current violations to
tools/rules/baseline/<rule>.txt.The rule skips baselined files, so only new violations fail.
Each time someone fixes a baselined file, they remove it from the list. A weekly job reports the remaining count.
The baseline is committed and reviewed. Adding a file to it requires a reason in the pull request, which keeps it from becoming an escape hatch.
Common mistakes
Mistake | Why it hurts | Do this instead |
|---|---|---|
Errors without a fix | Agents and people guess |
|
Regex for structural rules | False positives erode trust | Parser-based checks (go/analysis, AST) |
Only in pre-commit | Skipped with | Run the same scripts in CI |
New rule fails on all legacy code | Rule gets disabled | Baseline file, burn down over time |
One huge script for all rules | Hard to test and to own | One rule per script, one ID per rule |
Key takeaways
Write scripts for project-specific, checkable, repeatedly broken rules.
Print
path:line: RULE-ID messagewith the fix; agents correct named problems well.Use regex for text rules, real parsers for structural ones, and plain file logic for cross-file checks.
Run the scripts in pre-commit for speed and in CI for enforcement.
Introduce rules with a reviewed baseline so they can be strict from day one.
References
pre-commit, repository-local hooks: https://pre-commit.com/#repository-local-hooks
Go analysis framework: https://pkg.go.dev/golang.org/x/tools/go/analysis
Go singlechecker: https://pkg.go.dev/golang.org/x/tools/go/analysis/singlechecker
Rust std::fs: https://doc.rust-lang.org/std/fs/index.html
Node.js fs module: https://nodejs.org/api/fs.html
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.