/backend-pattern-rules:backend-pattern-rulesfrom backend-pattern-rules
Turn a backend codebase's own conventions into ast-grep lint rules with tests, or into the project's existing custom rule set (detekt, Error Prone, flake8/pylint plugins and similar), for Java, Kotlin, Python, Go, C#, PHP, Rust, Ruby, PowerShell (PSScriptAnalyzer rules) and other non-JS languages. Use when the user wants a custom lint rule or architecture check for backend code, asks which of their patterns, ADRs or CLAUDE.md / AGENTS.md instructions could become lint rules, asks which clean-code, bug-prevention, security or test rules the backend lacks, or wants to enforce a convention the code mostly follows. Not for JS, TS, Vue or Svelte code; use eslint-pattern-rules instead.
Ships in backend-pattern-rules. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A convention is what the codebase already mostly does, or what one of its decision records chose. This skill encodes one convention per rule, so the majority pattern becomes the only pattern. The project's code and decisions are the source of truth, and the user settles every design choice. Nothing is written until the user has picked it.
A rule also saves context: a convention written as prose in CLAUDE.md or AGENTS.md is read by every agent session, while a rule costs nothing until it is broken.
Rules are written for ast-grep: one YAML rule and one YAML test per convention, in any language ast-grep parses.
A check the project's own native linter or architecture test can already express wins over a custom rule.
When the project already maintains its own rule set for a native tool, new rules go into that rule set instead of ast-grep.
JavaScript and TypeScript, including Node backends, belong to the eslint-pattern-rules skill.
PowerShell has no ast-grep grammar: its rules are PSScriptAnalyzer rules, and references/powershell.md replaces the ast-grep parts of steps 1, 2, 4 and 5 for it.
Count and locate with rg -c / rg -n, always with a path (in scripts, rg without one waits on stdin) (with several -g globs the last matching one wins, so put exclusions like -g '!*.spec.ts' after the includes), confirm structural counts with ast-grep run -p '<pattern>' -l <lang>, and open a file only for details a count can't give.
Look each of these up rather than asking:
pom.xml, build.gradle(.kts), pyproject.toml, go.mod, *.csproj, composer.json, Cargo.toml, Gemfile, PowerShell sources (.ps1, .psm1).
Note the source roots, the test folders, and generated code (target/, build/, generated-sources/, migrations/, *_pb2.py, *.pb.go).sgconfig.yml, its ruleDirs and testConfigs, and how the project runs ast-grep (a pinned dependency, a CI step, a pre-commit hook).
Find the version to use with npm view @ast-grep/cli version when the project pins none.references/discovery.md step 1.RuleSetProvider, Error Prone BugCheckers, a PMD XPath ruleset, a flake8 or pylint plugin, go/analysis analyzers, Roslyn analyzers, PHPStan rules, or RuboCop cops.
Note its folder, base class, naming, test harness, how rules are registered and enabled, and any baseline file (detekt-baseline.xml, phpstan-baseline.neon)..yo-rc.json, .jhipster/, .openapi-generator/, @Generated, or DO NOT EDIT headers, and the source folders each generator owns.
A rule still guards new code there, but existing hits are fixed in the generator's template or blueprint, not by hand: say so for each hit in generated code.docs/adr/, docs/decisions/, notes/decisions/, ADR-*.md, CONTRIBUTING.CLAUDE.md, AGENTS.md and GEMINI.md in the repo, .github/copilot-instructions.md, .github/instructions/*.md, .cursor/rules/, .cursorrules, .windsurfrules.Done when you can state each of these in one line.
references/discovery.md step 4 first.
covered: report the existing check and stop.
built, not enabled: the job is enabling that rule, and how (everywhere, per module, with or without a baseline) is a design question in step 3.
Build what the user asked for; the rest of the ADR goes into the report under "not built".
When two ADRs say the same thing, link the newest accepted one and mention the other.
Note every agent-doc line that states the same convention, for step 6.references/discovery.md and follow it.
It covers the scan of code, decision records and agent docs, the general rules from references/general-rules.md, what is already enforced, risk, the mode question (automatic or manual), and the selection dialog.A tool counts as one the project runs when it runs in CI or a documented local check; a tool that is configured but never run (a Sonar file with no CI step), or configured for something else only (Checkstyle with just a NoHttp check), counts as built, not enabled for the conventions it could check.
A native check wins when a tool the project already runs can express the convention, including through a rule that tool has but the project has not enabled yet: a banned-API list (Ruff TID251, detekt ForbiddenMethodCall, golangci forbidigo/depguard, BannedApiAnalyzers, clippy disallowed_methods, forbiddenapis), a ready-made linter rule, or an architecture test library that is already a dependency (ArchUnit, Konsist, import-linter, Deptrac, NetArchTest).
Offer its exact config or test snippet as the candidate. Once picked, apply it and verify it with the project's own lint or test run instead of steps 4 and 5.
Set the tool's own message field as step 3 describes, and check that the lint or test run shows it: Ruff banned-api msg, detekt ForbiddenMethodCall and ForbiddenImport reason, golangci forbidigo msg and depguard desc, clippy disallowed-methods reason, the text after ; on a BannedSymbols.txt line, an ArchUnit rule's .because(...).
A tool the project does not run yet is never a reason to skip the rule: mention it in the report as an alternative instead.
ast-grep always counts as available, because it runs through npx without any project change.
A custom rule earns its place when the convention needs folder scoping, "only through our helper" logic, structural context, a tailored message or a fix.
Where a custom rule goes:
references/powershell.md.Done when every convention you will build has its good examples and its full violation list.
For each rule, work through these, skipping whatever the code already answers:
from .repository import, import x as y), type-only imports (if TYPE_CHECKING:), annotations, lambdas, nested functions, and fully qualified calls (java.time.Instant.now(), kotlin.io.println(...)).files and ignores globs.
Folder and package names live only in those globs and in one regex, so another layout needs only those values edited.fix when behavior is provably unchanged.
When a human should confirm, leave fix out and put the replacement in note.gen-<name> for ast-grep, the rule set's own naming otherwise).
The message says what is wrong, what to write instead, and where the rule comes from (ADR 0043, or the agent doc it replaces), in one sentence: once its agent-doc line is gone, the message is all an agent sees.
Severity is error, warning, info or hint.
Only error fails ast-grep scan, so a warning rule does not break CI until it is promoted, or CI runs ast-grep scan --error=gen-<name>.
In the project's rule set, use that tool's own severity and fail-threshold settings, and "safer" means the setting that does not fail the build.Ask with AskUserQuestion, in rounds of up to 4 questions whose prerequisites are settled.
Put your recommended answer first and label it "(Recommended)".
Show a real code example in the question or in an option's preview.
Without the tool, ask the same rounds as a numbered list in chat.
When the rule was selected automatically, or nobody can answer, answer with your recommendations and take the safer side: note over fix and the narrower scope.
Severity: always error.
With no open hits the rule goes in the main config, because nothing old breaks; with open hits it goes in the suggestions layer (step 4), so CI stays green while agent feedback loops, which block only on errors, still show it on new code.
Step 7 puts these answers to the user.
Done when every question has an answer and you know who gave it.
A rule for the project's own rule set follows Into the project's rule set below.
An ast-grep rule is exactly two files, both prefixed gen- so generated rules stay distinct from hand-written ones:
<rules-dir>/gen-<name>.yml
<tests-dir>/gen-<name>-test.yml
<rules-dir> and <tests-dir> come from an existing sgconfig.yml, or else are ast-grep/rules/ and ast-grep/rule-tests/ at the repo root.
The rule id is gen-<name>.
One rule covers one language: when a convention spans two languages, write gen-<name>-<lang> per language.
Hand-written rules stay as they are.
The rule file, with only the keys the rule needs. A comment at its top names the ADR, if any, and the values to edit for another layout:
id: gen-no-clock-in-domain
language: Java
severity: warning
message: Domain code takes a Clock instead of reading the system clock.
note: Inject `java.time.Clock` and call `Instant.now(clock)`.
files:
- src/main/java/com/acme/domain/**
rule:
any:
- pattern: Instant.now()
- pattern: System.currentTimeMillis()
The gotchas that bite here:
pattern must parse as code on its own.
When it doesn't (a method, an annotation, a class member), use pattern: {context: '<surrounding code>', selector: <kind>}.
When --debug-query=ast shows ERROR nodes in a pattern, switch to kind plus a regex on the relevant child.kind names come from the language's tree-sitter grammar.
Look them up with ast-grep run -p '<sample code>' -l <lang> --debug-query=ast, never guess.$A matches one node, $$$A zero or more, $_ one without capturing.
The same name used twice must match identical code.inside and has look only one level up or down unless they set stopBy: end.field: <name> constrains the node's position in its parent, so it belongs on the level whose node sits in that field.
has: {field: name} checks only the first child in that field: on from x import a, b it never sees b.
Drop field when any child may match.kind) with has a child whose text matches one module-name regex, which covers absolute and relative forms at once.
Test every form the language has: plain, from-imports, multi-name and parenthesized, aliased, wildcard, static, relative, and function-local imports.f($A, $$$B) needs the comma, so it never matches a single-argument call: add f($A) as a second pattern.$S in f($S) is a value_argument, so constraints: {S: {kind: string_literal}} never matches.
Check with --debug-query=ast, and constrain with regex or has instead.(^|\.)Instant$, not ^Instant$, so java.time.Instant.now() is caught too.regex is Rust regex: no lookahead or lookbehind.Build the tests from the real code:
valid: the convention and every allowed edge case.invalid: each kind of violation.files and ignores, so scope is checked in step 5, not here.id: gen-no-clock-in-domain
valid:
- Instant.now(clock);
invalid:
- |
class Order { boolean expired() { return expiresAt.isBefore(Instant.now()); } }
Build files stay byte-identical.
Never add ast-grep or any other dependency to pom.xml, build.gradle, pyproject.toml, go.mod, a .csproj, composer.json, Cargo.toml, Gemfile or a lockfile.
When the project does not run ast-grep yet, call it without installing it: npx -y -p @ast-grep/[email protected] ast-grep or uvx --from ast-grep-cli==x.y.z ast-grep.
Never call it as sg, which is a different system command on Linux.
The install command and a CI step go into the report.
Register the rule yourself, without asking: it is part of building the rule, not a design choice.
With an existing sgconfig.yml, the rule is picked up from its ruleDirs, and nothing else changes.
Without one, create sgconfig.yml at the repo root:
ruleDirs: [ast-grep/rules]
testConfigs:
- testDir: ast-grep/rule-tests
When step 2 chose the project's own rule set, its existing rules are the template, and this replaces the ast-grep files above:
gen- prefix.
Name the rule Gen<Name> only when its rules have no naming pattern to follow.url, a message suffix), the new rule carries its ADR the same way.lint() / compileAndLint, Error Prone CompilationTestHelper, pytest with the plugin's fixtures, analysistest), with the same valid and invalid coverage as above.RuleSetProvider, a service file, an entry point), and enable it in the project's lint config at the agreed severity, the same way the others are enabled.
When rules are enabled both in a shared config and in per-module overlays, enable it at the level the rollout answer chose.
Leave every other config entry as it is.detekt-baseline.xml, phpstan-baseline.neon) on your own.
Report the hits, and offer the baseline as a design question when the user wants the rule enforced only for new code.Suggestions layer, for a rule the existing code breaks.
At error in the main config it would fail ast-grep scan and CI on day one; at warning a feedback loop never shows it, since loops block only on errors.
So it goes into a second rule folder at error, which the main config does not load:
ast-grep/suggestions/gen-<name>.yml (beside the project's rule folder), its test in the usual test folder;sgconfig.suggestions.yml in the root: the main config's content with the suggestions folder added to ruleDirs:
ruleDirs: [ast-grep/rules, ast-grep/suggestions]
testConfigs:
- testDir: ast-grep/rule-tests
sgconfig.yml stays as it is, so ast-grep scan and CI see only the main rules, and plain ast-grep test skips the suggestion tests; ast-grep test -c sgconfig.suggestions.yml tests every rule, so propose that as the CI test step.ast-grep scan -c sgconfig.suggestions.yml <files>.--config base.yml,suggestions.yml, Ruff --config ruff.suggestions.toml with extend = "pyproject.toml"), or its baseline as a design question.For a rule in the project's rule set, run its module's tests, then the project's lint task over the real code (./gradlew detekt, mvn compile with Error Prone, flake8, golangci-lint run), and work through steps 4 and 5 below with that output.
A baseline can hide hits: rg -c <rule-id> over the baseline files first, and when they hold entries, count from a run with the baseline disabled, if the tool allows it, or report the hidden count.
ast-grep test --skip-snapshot-tests until the cases pass.ast-grep test --update-all, read the generated __snapshots__/gen-<name>-snapshot.yml, and confirm each label (and fixed output, with fix) is what you expect.
Then ast-grep test passes as it will in CI.ast-grep scan --filter '^gen-<name>$'.
Add --json=compact to count hits.valid test and a rule fix, then a rerun.
A file in scope with no hit that should have one becomes an invalid test.ast-grep scan once, to confirm sgconfig.yml loads and reports gen-<name>; for a suggestion rule, run ast-grep scan -c sgconfig.suggestions.yml for that, and confirm plain ast-grep scan reports nothing new.Done when the tests pass with snapshots, every hit is accounted for, the project-wide scan reports the rule, and its message names its source.
Only for a rule built or enabled in this run and verified (a custom rule through step 5, a config change through the project's own lint run), and only for the agent-doc lines that state the convention it now enforces.
A rule in the suggestions layer counts: a feedback loop that runs the suggestions config shows it on every changed line.
Without such a loop, say in the question that only people who run the suggestions config see it.
The cleanup always asks, in both modes: it changes a doc.
In manual mode, ask one AskUserQuestion per rule; in automatic mode, ask the lines of every built rule in one call after the builds.
Quote each line with its file and line number:
Time: inject a Clock, never call now() directly (enforced by gen-no-clock-in-domain).: recommended when the convention shapes code before it is written, so an agent that never saw it would build the wrong thing and redo it.
The pointer goes where the agent will load it: a CLAUDE.md in the folder the rule applies to, or an instructions file with an applyTo glob for those paths.
A pointer left only in a file the agent has to follow a link to read is not seen up front, so propose the place in the same question.Before recommending a delete, make sure the rule's message carries what the line said, plus the ADR link if there is one. A built-in rule whose tool has no message field, or whose message does not carry the line, never gets the delete option: offer the pointer or keep. Edit the doc only as answered, and never touch a line no verified rule covers. With nobody to answer, change no doc and list the lines in the report.
Done when every covered line is answered or listed.
Keep it short:
sgconfig.yml or the lint-config change, as a short diffast-grep test && ast-grep scan), when the project does not run ast-grep yetcodemyrules feedback loop; without it a broken rule only surfaces in CI, after the sessionIf you answered design questions on the user's behalf, close with one AskUserQuestion round that presents those answers, with yours as the first option.
Apply the changes, then rerun step 5 for that rule.
With nobody to answer, end the report with those answers as a numbered list instead, each with its reason and the alternative.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
backend-pattern-rules@codemyrules is listed by clirimajeti/codemyrules — review the source before installing
npx claudepluginhub clirimajeti/codemyrules --plugin backend-pattern-rules