ast-grep
Skill10 starsChanged yesterdayMITView on GitHub
Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search. This skill should be used when users ask to search for code patterns, find specific language constructs, or locate code with particular structural characteristics.
23 other projects use a version of this, 10 of them edited.
Adopted by
Most recently taken up by
- matt-riley/agent-skillstheir own version, first seen Nov 15, 2026
- coleam00/skillsedited, first seen Nov 14, 2026
- zxyycom/skillstheir own version, first seen Nov 8, 2026
- hugefiver/dsmmtheir own version, first seen Nov 1, 2026
- AprilNEA/OpenLogiedited, first seen Oct 17, 2026
- nobodyohm-web/Thottheir own version, first seen Oct 13, 2026
Used with
Projects with it also use rust, create-pr and 3 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
MicrosoftSkillrust
Use this guide when working on Rust changes in the FAST monorepo.
Also in 3 projects that use this
SentrySkillcreate-pr
Create pull requests following Sentry conventions. Use when opening PRs, writing PR descriptions, or preparing changes for review. Follows Sentry's code review guidelines.
Also in 4 projects that use this
GoogleSkilltdd
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
Also in 4 projects that use this
SentrySkillskill-creator
Create new agent skills following the Agent Skills specification. Use when asked to "create a skill", "add a new skill", "write a skill", "make a skill", "build a skill", or scaffold a new skill with SKILL.md. Guides through requirements, writing, registration, and verification.
Also in 5 projects that use this
- +1 more from getsentry
Other versions23 projects use a version of this.
Word for word · 0
None found.
Edited · 10
- AprilNEA/OpenLogi★ 26k100% same
- warp-drive-data/warp-drive★ 3.2k98% same
- coleam00/skills★ 73899% same
- nodetool-ai/nodetool★ 63791% same
- moeru-ai/auv★ 20799% same
- ulpi-io/browse★ 1543% same
- trotsky1997/My-Claude-Agent-Skills★ 799% same
- tentacle-pro/skills★ 499% same
- acgs-ai/ACGS★ 299% same
- phalbohr/skills★ 199% same
Wrote their own version · 13
- ryoppippi/ccusage★ 19ksame name
- ccusage/ccusage★ 19ksame name
- damusix/skills★ 63same name
- tstapler/dotfiles★ 8same name
- drunkcoding/AgentSkillsArxiv★ 5same name
- rolandbrecht/agent-skills★ 4same name
- matt-riley/agent-skills★ 3same name
- shalomb/agent-skills★ 3same name
- tizee/skills★ 2same name
- zxyycom/skills★ 2same name
3 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository44 other files it gives its agents.
- llms-full.txtllms.txt
- llms.txtllms.txt
- ai-prompt-engineering-safety-reviewSkill
- ast-codemapSkill
- autoharnessSkill
- autonomous-backlog-driverSkill
- claude-kimi-mcp-normalizationSkill
- cli-self-updaterSkill
- code-frugalitySkill
- codemode-gatewaySkill
- codemode-typesSkill
- consequence-simulationSkill
- context-pruningSkill
- github-update-checkerSkill
- google-agents-cli-evalSkill
- google-agents-cli-scaffoldSkill
- history-searchSkill
- hook-gatingSkill
- hybrid-semantic-searchSkill
- kimi-code-agent-integrationSkill
- kimi-mcp-configurationSkill
- leann-vectorSkill
- log-summarizerSkill
- markdown-vagueSkill
- memory-reconciliationSkill
- mode-classificationSkill
- multiagent-orchestrationSkill
- output-compressionSkill
- prompt-injectionSkill
- python-anti-patternsSkill
- regression-sentinelSkill
- restart-trackingSkill
- rollback-guardSkill
- rust-call-graphSkill
- secrets-managementSkill
- security-best-practicesSkill
- session-compactorSkill
- sqlite-memorySkill
- swarm-barrierSkill
- swarm-dagSkill
- autoharnessSkill
- code-reliability-checksSkill
- skill-threat-rulesSkill
- autoharnessSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
25 rules. 0 are common, 12 are distinctive, and 13 are very specific to this project.
0
Common
Most of the 22 edited versions we read keep these.
12
Distinctive
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
Use this skill when users:
- Distinctive: line 18
Ask to search for code with particular AST characteristics
- Distinctive: line 23
Follow this process to help users write effective ast-grep rules:
- Distinctive: line 35
Write a simple code snippet that represents what the user wants to match.
- Distinctive: line 38
If searching for "async functions that use await", create a test file:
- Very specific: line 53
Always use stopBy: end for relational rules (inside, has) to ensure search goes to the end of the direction
- Very specific: line 54
Use pattern for simple structures
- Very specific: line 55
Use kind with has/inside for complex structures
- Distinctive: line 73
Use ast-grep CLI to verify the rule matches the example code.
- Very specific: line 93
Add stopBy: end to relational rules if not present
- Very specific: line 94
Use --debug-query to understand the AST structure (see below)
- Very specific: line 95
Check if kind values are correct for the language
- Distinctive: line 157
Test a rule against code snippet without creating files:
- Distinctive: line 189
When you don't need relational rules (inside/has)
- Distinctive: line 241
When you need the power of full YAML rules
- Very specific: line 263
If that doesn't work, try kind to match the node type
- Very specific: line 264
Add relational rules (has, inside) as needed
- Distinctive: line 275
When rules don't match:
- Very specific: line 276
Use --debug-query=cst to see the actual AST structure
- Distinctive: line 277
Check if metavariables are being detected correctly
- Very specific: line 278
Verify the node kind matches what you expect
- Distinctive: line 279
Ensure relational rules are searching in the right direction
- Very specific: line 290
When using --inline-rules, escape metavariables in shell commands:
- Very specific: line 291
Use \$VAR instead of $VAR (shell interprets $ as variable)
- Very specific: line 359
When a rule still fails after --debug-query and the rule reference, read the official docs:
“Common” is measured: kept by at least 6 in 10 of the 22 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
ast-grep Code Search
Overview
This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text, enabling powerful and precise code search across large codebases.
When to Use This Skill
Use this skill when users:
- Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")
- Want to locate specific language constructs (e.g., "find all function calls with specific parameters")
- Request searches that require understanding code structure rather than just text
- Ask to search for code with particular AST characteristics
- Need to perform complex code queries that traditional text search cannot handle
General Workflow
Follow this process to help users write effective ast-grep rules:
Step 1: Understand the Query
Clearly understand what the user wants to find. Ask clarifying questions if needed:
- What specific code pattern or structure are they looking for?
- Which programming language?
- Are there specific edge cases or variations to consider?
- What should be included or excluded from matches?
Step 2: Create Example Code
Write a simple code snippet that represents what the user wants to match. Save this to a temporary file for testing.
Example: If searching for "async functions that use await", create a test file:
// test_example.js
async function example() {
const result = await fetchData();
return result;
}Step 3: Write the ast-grep Rule
Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.
Key principles:
- Always use
stopBy: endfor relational rules (inside,has) to ensure search goes to the end of the direction - Use
patternfor simple structures - Use
kindwithhas/insidefor complex structures - Break complex queries into smaller sub-rules using
all,any, ornot
Example rule file (test_rule.yml):
id: async-with-await
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: endSee references/rule_reference.md for comprehensive rule documentation.
Step 4: Test the Rule
Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:
Option A: Test with inline rules (for quick iterations)
echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" --stdinOption B: Test with rule files (recommended for complex rules)
ast-grep scan --rule test_rule.yml test_example.jsDebugging if no matches:
- Simplify the rule (remove sub-rules)
- Add
stopBy: endto relational rules if not present - Use
--debug-queryto understand the AST structure (see below) - Check if
kindvalues are correct for the language - For zero matches from
run --pattern(not rules), see the "Zero Matches?" tip below
Step 5: Search the Codebase
Once the rule matches the example code correctly, search the actual codebase:
For simple pattern searches:
ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/projectFor complex rule-based searches:
ast-grep scan --rule my_rule.yml /path/to/projectFor inline rules (without creating files):
ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
pattern: \$PATTERN" /path/to/projectast-grep CLI Commands
Inspect Code Structure (--debug-query)
Dump the AST structure to understand how code is parsed:
ast-grep run --pattern 'async function example() { await fetch(); }' \
--lang javascript \
--debug-query=cstAvailable formats:
cst: Concrete Syntax Tree (shows all nodes including punctuation)ast: Abstract Syntax Tree (shows only named nodes)pattern: Shows how ast-grep interprets your pattern
Use this to:
- Find the correct
kindvalues for nodes - Understand the structure of code you want to match
- Debug why patterns aren't matching
Example:
# See the structure of your target code
ast-grep run --pattern 'class User { constructor() {} }' \
--lang javascript \
--debug-query=cst
# See how ast-grep interprets your pattern
ast-grep run --pattern 'class $NAME { $$$BODY }' \
--lang javascript \
--debug-query=patternTest Rules (scan with --stdin)
Test a rule against code snippet without creating files:
echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" --stdinAdd --json for structured output:
echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --jsonSearch with Patterns (run)
Simple pattern-based search for single AST node matches:
# Basic pattern search
ast-grep run --pattern 'console.log($ARG)' --lang javascript .
# Search specific files
ast-grep run --pattern 'class $NAME' --lang python /path/to/project
# JSON output for programmatic use
ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .When to use:
- Simple, single-node matches
- Quick searches without complex logic
- When you don't need relational rules (inside/has)
Reading --json Output
--json prints a bare JSON array of matches (no matches wrapper). For pattern foo($ARG, $$$REST):
[{
"text": "foo(\"value\", 1, 2)",
"file": "src/app.js",
"range": { "start": { "line": 41, "column": 10 }, "end": { "line": 41, "column": 27 } },
"metaVariables": {
"single": { "ARG": { "text": "\"value\"" } },
"multi": { "REST": [ { "text": "1" }, { "text": "2" } ] }
}
}]scan --json uses the same schema.
(Each match also includes lines and language.) range.start.line is 0-based. Named metavariables ($ARG) land in single, list metavariables ($$$REST) in multi as a list (empty if nothing captured). Extract with jq:
ast-grep run --pattern 'foo($ARG)' --lang javascript --json . \
| jq -r '.[] | "\(.file):\(.range.start.line + 1): \(.metaVariables.single.ARG.text)"'Search with Rules (scan)
YAML rule-based search for complex structural queries:
# With rule file
ast-grep scan --rule my_rule.yml /path/to/project
# With inline rules
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" /path/to/project
# JSON output
ast-grep scan --rule my_rule.yml --json /path/to/projectWhen to use:
- Complex structural searches
- Relational rules (inside, has, precedes, follows)
- Composite logic (all, any, not)
- When you need the power of full YAML rules
Tip: For relational rules (inside/has), always add stopBy: end to ensure complete traversal.
Tips for Writing Effective Rules
Always Use stopBy: end
For relational rules, always use stopBy: end unless there's a specific reason not to:
has:
pattern: await $EXPR
stopBy: endThis ensures the search traverses the entire subtree rather than stopping at the first non-matching node.
Start Simple, Then Add Complexity
Begin with the simplest rule that could work:
- Try a
patternfirst - If that doesn't work, try
kindto match the node type - Add relational rules (
has,inside) as needed - Combine with composite rules (
all,any,not) for complex logic
Use the Right Rule Type
- Pattern: For simple, direct code matching (e.g.,
console.log($ARG)) - Kind + Relational: For complex structures (e.g., "function containing await")
- Composite: For logical combinations (e.g., "function with await but not in try-catch")
Debug with AST Inspection
When rules don't match:
- Use
--debug-query=cstto see the actual AST structure - Check if metavariables are being detected correctly
- Verify the node
kindmatches what you expect - Ensure relational rules are searching in the right direction
Zero Matches? Patterns Match Whole AST Nodes
run --pattern matches complete AST nodes, not text substrings, so zero matches can mean "code absent" or "pattern has the wrong node shape":
- Qualified paths are whole nodes:
env::var($ENV)does NOT matchstd::env::var("X"). Try both bare and fully-qualified forms, or use$$$to absorb extra intermediate nodes. - To tell them apart: test the pattern on a snippet known to contain the code, and inspect how ast-grep parsed it with
--debug-query=pattern(works forrun, not justscan/rules). For zero matches from rules instead, follow the Step 4 debugging checklist.
Escaping in Inline Rules
When using --inline-rules, escape metavariables in shell commands:
- Use
\$VARinstead of$VAR(shell interprets$as variable) - Or use single quotes:
'$VAR'works in most shells
Example:
# Correct: escaped $
ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" .
# Or use single quotes
ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .Common Use Cases
Find Functions with Specific Content
Find async functions that use await:
ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end" /path/to/projectFind Code Inside Specific Contexts
Find console.log inside class methods:
ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
pattern: console.log(\$\$\$)
inside:
kind: method_definition
stopBy: end" /path/to/projectFind Code Missing Expected Patterns
Find async functions without try-catch:
ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end
- not:
has:
pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
stopBy: end" /path/to/projectResources
references/
Contains detailed documentation for ast-grep rule syntax:
rule_reference.md: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables
Load these references when detailed rule syntax information is needed.
Online documentation
When a rule still fails after --debug-query and the rule reference, read
the official docs:
https://ast-grep.github.io/llms.txtindexes every docs page; fetch the one page you need (each is linked as a.mdfile, such ashttps://ast-grep.github.io/guide/rule-config/relational-rule.md).https://ast-grep.github.io/llms-full.txtholds all the docs in one file of about 850 KB. Download it and search it; never read it whole.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

