/search:ast-grepfrom search
Use when outlining, searching, or rewriting code with ast-grep or writing a rule, covering matching and rule configuration
Ships in search. 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.
Search rules stay inline, durable rules sit under ruleDirs. Rules take no test folder or testConfigs row, the repository scan checks each one.
[REFERENCES]:
[TEMPLATES]:
Patterns are valid code under the language's tree-sitter grammar with whole-node metavariables:
$VAR one named node, $$VAR one named or unnamed node (operators and keywords included)$$$MULTI lazy zero-or-more without backtracking, $_ and $_NAME non-capturing$$$ before a node ends at the first fitting sibling, f($$$H, { $$$P }, $$$T) matches f(x, { a }, { b })$$$A, $$$B loses a node on f(a, b, c), A binds empty and B starts at the separator$$$A holds separators, comments, and a trailing comma as nodes, transforms read its full source span"$A" binds string content, the metavariable test reads any node's whole text, a string holding an escape has more children and misses$x, $0, and $@ match as literal text (Bash expansions included)Compilation peels single-child wrappers, the pattern's root decides the match range:
a selects the identifier, a; the expression_statement, pass the anonymous token inside pass_statementkind refuses and supply a kind set, {pattern: pass, inside: {kind: pass_statement}}pattern: {context: <full-code>, selector: <kind>}, run takes -p <full-code> --selector <kind>selector takes one kind name and selects its first pre-order node, defining metavariables inside it alone, a lone selected metavariable matches its kindkind load and never match, run alone reports them at zero matches, without kind the load failsStrictness decides which nodes matching skips, the levels hold no total order:
| [INDEX] | [LEVEL] | [SKIPS] |
|---|---|---|
| [01] | cst | Nothing |
| [02] | smart | Unnamed target nodes, grammar extras, every target child past the pattern's last |
| [03] | ast | Unnamed nodes on both sides |
| [04] | relaxed | Unnamed nodes on both sides, grammar extras |
| [05] | signature | Text of leaves, matched by kind alone, capture identity kept |
| [06] | template | Kinds, matched by text alone, a kind sits beside it |
import a matches import a, b under smart alonesmart, cst, template require the comma before $$$, f($A, $$$R) matches f(x,) and misses f(x), ast, relaxed, signature bind R empty$X binds a comment under smart, the skip test reads the grammar's extras, relaxed skips every extrarun filters files by the pattern's longest literal whatever the strictness, --strictness signature misses files lacking it where scan finds themPatterns debug through --debug-query, pattern prints the compiled pattern with its peeled root, cst and ast a tree, sexp an S-expression:
regex is a Rust regex with Unicode \w, \s, \d, \b, no look-around or back-reference, and (?i) flags inline, a class over source characters restates a grammar token a kind test states:
word rule, else the rule name fields hold most often (Swift simple_identifier)extras where it states that set (Swift [\t-\r ] under \s+)(?-u:\s) reads ASCII[0-9A-Za-z_], [\t\n\v\f\r ], [0-9], and (?-u:\b), an ASCII class over a Unicode identifier token (Java) misses names[^\t\n\v\f\r ]) match every non-ASCII character(?x) in a |- block scalar holds one alternative per line with \ for a space inside a phrase, (?-x:...) keeps a phrase verbatimIdentifier tokens hold Unicode classes per grammar, JavaScript and TypeScript accepting \u escapes:
| [INDEX] | [LANGUAGE] | [START] | [CONTINUE] |
|---|---|---|---|
| [01] | Rust | (r#)?[_\p{XID_Start}] | [_\p{XID_Continue}]* |
| [02] | Python | [_\p{XID_Start}] | [_\p{XID_Continue}]* |
| [03] | JS, TS | Continue set, no digit | No C0 control, \p{Zs}, ASCII punctuation but $ _, U+200B, U+2028, U+2029, U+2060, U+FEFF |
Rule documents load through one strict deserializer:
<stem>-<index>, every util declares id<category>-<language>, in one the category aloneDuplicate rule id, unknown rule-document keys fail deserializationnot: or has: keys in one map fail the load as duplicate mapping key: <key>, not: {any: [<guards>]} or an all: holds both{kind: 'block_mapping_pair, flow_pair'}), an unquoted second kind reads as a keyseverity is hint, it prints help[<id>] and exits 0, off removes the rulemetadata is a mapping printed under --include-metadata alone, url reaches LSP code_description aloneRule maps conjoin pattern, kind, regex, nthChild, range, all, any, not, matches, then inside, has, precedes, follows whatever the YAML key order, a cheap relation beside a costly any, not, or matches runs first only from an ordered all:
kind, pattern, matches, or nthChild.ofRule predicates can derive candidate kindsregex, range, not, inside, or unfiltered nthChild alone, utils under them included, fail with Rule must specify a set of AST kinds to matchpattern: $X alone supplies no kind set, matches inherits kinds from its selected utilany: arms remove the kind set, a sibling kind restores it and alone the rule fails to load, all: narrows to the intersection of its itemsany: [] load and never match, all: [] fails the loadkind holds a selector language:
,, >, a space, +, ~ and :has(), :not(), :is(), :nth-child(An+B of S), :nth-last-child() compile to matchers:first-child, *, .x, [x], field selectors, and an anonymous token (then) fail the load with Cannot parse rule:has(> a b) tests b as the direct child, + reads the adjacent sibling tokens included, number + identifier misses [1, b] where ~ holdsexpression, statement) load and match nothing, a rule lists their subtypeskind: ERROR matches, parse failures otherwise silence a rule at exit 0 and read as conforming codelazy import, C# 14 extension blocks) as ERRORERROR regions, and a kind: ERROR rule flags valid code therekind: MISSING fails the load, an inserted token keeps its kind as a zero-width leaf regex: '^$' matches, beside an exemption for kinds zero-width when validPositions:
nthChild is 1-based and takes An+B strings, it counts named siblings and comments, a slot takes ofRule naming its kind or excluding every comment kindnthChild never matches the root, reverse takes the object form beside positionofRule requires the target to match it as well, its metavariable binds the target alonerange is exact on both endpoints, lines and columns are 0-based, columns count characters, column is optionalRelations test one node along one axis:
has: {all: [<a>, <b>]} demands one child with both shapes, one has per required childfield and stopBy, has: {field: <role>} alone fails with Rule must have one positive matcherstopBy default neighbor reads direct relations, a rule stopBy ends the walk at the first node it matches, that node includedstopBy: {not: {kind: W}} walks through a chain of W and stops at the first other node, a climb through parentheses alonestopBy rules start fresh captures and discard bindings, relation targets retain caller capturesstopBy: end walks a candidate's whole axis (has the subtree, inside every ancestor, follows and precedes every sibling on that side)return, depth, and locals, a module for imports), wider walks cost time and false findingsfield: binding names the final relation and survives stopBy: end (callee vs argument, key vs value)has with field and a rule stopBy reads the field child and its children alone and misses ((b)), has: {field: <role>, any: [<target>, {kind: <wrapper>, has: {stopBy: <stop>, <target>}}]} descendsoperator) take has: {field: <role>, pattern: $$_X}has and inside with field test a repeated field's first child alone, later children take a fieldless relation with kind and direct parentfollows and precedes read the adjacent sibling, a comment or unnamed token (,) between siblings takes a stopByfollows and precedes walks locate the candidate by its start byte, under an error-recovered parent they can yield no siblinghas visits unnamed children and comments, restrict named children with not: {has: {pattern: $_, not: {any: [<allowed>, {kind: <comment kinds>}]}}}Captures bind in clause order and export from what matched:
not guards over a capture sit after its binding clause in all:, the first clause naming $VAR binds any candidate in place of testing equality$VAR stores the last matching node and range, $_VAR skips capture and comparison$VAR compares text when either side has no named children whatever the kinds (property y equals identifier y)$VAR over named children needs the same kind and child count recursively, whitespace is ignored, comments count ((a) differs from a)not reads current captures and discards new bindings, double negation still exports nonenot: {has: ...} or not: {inside: ...} stopping at owner kinds, the form for a fact every sibling repeatsall, relational rules, and the matching any: arm export to fix, message, and transformany: arms bind nothing, the next arm binds the same name againany: whose last arm always matches, a template over the unbound capture renders emptyany: keeps the first structurally matching arm with no constraints retry, the wrapped pattern precedes the unwrapped oneConstraints test single captures after the rule matches, in unspecified order, $$$ captures pass unfiltered:
{A: {not: {has: {pattern: $K, stopBy: end}}}} relates capture A to capture Kconstraints: {A: {pattern: 'g($Z)'}} exports $Z to fix$, a transform output is rejected as undefined, a capture unbound in the chosen any: arm passes<package>-<shape> and read id, language, arguments, rule, constraints, utils, and transform, other keys load unread$NAME binds afresh untested against the caller's, fix: $P over one fails as undefinedutilDirs load for directory scans, scan -r, and --inline-rules, stdin included, -r and --inline-rules load no project rule directoryall beside kind loads and matches, a parameter slot contributes nonearguments at the global level alone, a local 'wrap(NAME)' exits 8, arguments are mandatory, a string matches: <id> of a parameterized util exits 8matches: {<util-id>: {<arg>: <rule>}}, each argument a rule, calls under one matches combine as allRule <id> is not defined where load order reaches the caller first, a local util holding one orders itmatches, under all or not) order the load and keep the relational callmatches: <name> resolves a parameter, then a local util, then a global utilfix reading them prints empty{pattern: $X} binding the first candidate a util's relation visits, a name test calls the util at that namerule, an argument read in constraints or a nested call exports noneParameterized call exporting argument captures, with a recursive util consuming strict descendants through has, each util in its own utilDirs file:
id: call-with
language: javascript
arguments: [CALLEE, ARG]
rule:
kind: call_expression
all:
- has: {field: function, matches: CALLEE}
- has: {field: arguments, has: {matches: ARG}}
---
id: wrapped-number
language: javascript
rule:
any:
- kind: number
- kind: parenthesized_expression
has: {matches: wrapped-number}
---
id: no-numeric-send
language: javascript
severity: error
message: $NAME takes $VALUE
rule:
matches:
call-with:
CALLEE: {regex: '^send', pattern: $NAME}
ARG: {matches: wrapped-number, pattern: $VALUE}
fix: $NAME(String($VALUE))
Over send(1), sendAll(((2))), send(x), send(g(3)), other(1):
send(1) -> send(String(1)) | send takes 1
sendAll(((2))) -> sendAll(String(((2)))) | sendAll takes ((2))
fix replaces the whole matched node with a template, transform derives text, and rewriters change structure inside captures:
if (a) b; with fix X turns if (a) b; else c; into X, strictness: ast or a not: {has: ...} guards itscan and substitute empty under run -r$NAME comes from a replace with by: $$NAME;, a template without the terminator drops itq($S) over f($S) adds that indent inside a multiline string, a match narrowed to the changed token keeps its contentsprogram-level fix blocks every other fix-U applies only the outer of nested same-rule matches per pass, f(f(1)) becomes g(f(1)), a rerun reaches the inner oneTemplate names read greedily over [A-Z0-9_]:
$A_x and $A1 fail the load as undefined A_ and A1, $Ax prints the capture then x$A on a $$$A capture, $$$A on a single capture, and $$$T on a transform output load and print nothingmessage substitutes captures and transform outputs with no load check, an unknown name prints empty, note and label message stay literalby: '$1x' reads a group named 1x and prints empty, ${1}x holds the group apartTransforms name outputs without $ and read their source with $:
Transform var <name> has already defined, one reading itself as cyclic dependency\A replace fires, a prefix belongs on the transform reading the captureNEW: replace($OLD, replace=<regex>, by=<text>) replaces textNEW: substring($OLD, startChar=1, endChar=-1) uses constant character indexes, negatives count from the endNEW: convert($OLD, toCase=snakeCase, separatedBy=[underscore]) converts case over the named separatorsNEW: rewrite($OLD, rewriters=[<id>]) rewrites nodesby="x,y" holds, 'it''s' fails, object forms (replace: {source: $OLD, replace: <regex>, by: <text>}) take any value\\dreplace reads Rust regex captures in its by field as $1 or ${NAME}, with $$ for a literal dollarRewriters sit in the document rewriters list and hold id, rule, and fix, optional constraints, transform, and utils, and accept kindless field predicates:
$$$ capture included, anonymous tokens through a kindless regex ({regex: '^,$'})joinBy omitted keeps unmatched text, separators and comments between rewritten nodes included, joinBy set joins the replacements alonejoinBy omitted and empty with it set, a filtering rewriter sets joinBytransform, f(g(h(1))) gives <g>, a rewrite over $X inside it gives <g <h 1>>{has: {kind: identifier}} rewrites [a, b] to [X, b], {kind: array, has: ...} gives XjoinBy: "" gives an optional segmentrewriters: key, with the key they fail as Undefined rewriterutils share the document's namespace, one util name in the rule and a rewriter fails as Duplicate rule idjoinBy absent (expandEnd, expandStart, a lone inside), joinBy takes a path with no slicing--stdin, on a file it kills a worker thread at exit 0 with []Filtering rewriters split a list by member shape:
id: split-args
language: javascript
severity: error
message: split $NAME
rule: {pattern: $NAME($$$ARGS)}
rewriters:
- {id: keep-numbers, rule: {kind: number, pattern: $V}, fix: $V}
- {id: keep-names, rule: {kind: identifier, pattern: $V}, fix: $V}
transform:
NUMBERS: {rewrite: {source: $$$ARGS, rewriters: [keep-numbers], joinBy: ', '}}
NAMES: {rewrite: {source: $$$ARGS, rewriters: [keep-names], joinBy: ', '}}
fix: "$NAME([$NUMBERS], [$NAMES])"
mix(1, a, 2, /* c */ b) -> mix([1, 2], [a, b])
mix(a) -> mix([], [a])
fix: {template, expandStart, expandEnd} widens the replaced range to the sibling the sub-rule matches, a miss keeps the matched range:
stopBy: end the first match past others (not: {regex: '^=$'} reaching a value past =)field beside them is ignoredfix as a list of {title, template} offers alternatives, -U and --json take the first and -i offers eachList member removal takes expandEnd only when no comma precedes, one fix covers every position:
id: drop-arg
language: javascript
severity: error
message: drop x
rule: {kind: identifier, regex: '^x$', inside: {kind: arguments}}
fix:
template: ''
expandStart: {regex: '^,$'}
expandEnd: {regex: '^,$', not: {follows: {regex: '^,$', stopBy: end}}}
f(a, x, b); -> f(a, b);
f(a, x); -> f(a);
f(x, b); -> f( b);
f(x); -> f();
f(a, x,); -> f(a,);
Labels:
labels: key replaces them all, an unbound label dropslabels highlights captured AST ranges, transformed text has no source range, local util captures can label a match and global ones cannotast-grep-ignore comments read node kinds containing comment with the marker as their first alphabetic text:
ast-grep-ignore foo and ast-grep-ignore-foo includedq because, p suppresses q and p, prose after an id is allowedPatterns and inline rules sit in single quotes, keeping $VAR from the shell, and $'...' reads \n as a newline and \\ as one backslash.
Syntax trees and compiled patterns on stderr:
ast-grep run -l <lang> -p '<code>' --debug-query=cst
ast-grep run -l <lang> -p '<pattern>' --selector <kind> --debug-query=pattern
Matches with file, line, and capture, --json=stream objects holding file, text, lines, range, and metaVariables:
ast-grep run -p '<pattern>' --json=stream <paths> | jq -r '"\(.file):\(.range.start.line+1) \(.metaVariables.single.<VAR>.text)"'
ast-grep run -p '<pattern>' --files-with-matches <paths>
ast-grep run -p '<pattern>' --globs '<glob>' -C <n> <paths>
Rule matches over a snippet, paths, or project rules, --max-results on scan alone:
printf '%s' '<code>' | ast-grep scan --stdin --inline-rules $'<rule>' --json=stream
ast-grep scan --inline-rules $'<rule>' --report-style short --max-results <n> <paths>
ast-grep scan --filter '<id regex>' --json=stream <paths> | jq -r .ruleId | sort | uniq -c
ast-grep scan -r <rule.yml> --report-style short <paths>
Rewrites print a diff, -U writes it:
ast-grep run -p '<pattern>' -r '<template>' <paths>
ast-grep scan -r <rule.yml> -U <paths>
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub bsamiee/rasm --plugin search5 skills in this plugin
/arenaUse when a task reads or writes Are.na channels, blocks, users, or groups, covering search, channel reads, image and file retrieval, and connections/codeUse when a task needs a fact about a dependency or a survey of many repositories, covering source selection by fact kind and GitHub quota/notebooklmInstall, authenticate, troubleshoot, and operate Gemini Notebook through the notebooklm-py CLI or typed async Python API. Use for notebook and source management, grounded chat and research, and artifact generation or download when the user mentions Gemini Notebook, notebooklm-py, the notebooklm CLI, or its Python API. Do not use for the generic Gemini API or unrelated content creation./webUse when a task needs an answer from the open web, covering tool selection by source and evidence