agentleFS
rolandbrechtrolandbrecht/agent-skills/ast-grep/SKILL.md

ast-grep

Skill4 starsChanged 3 months agoMITView on GitHub

AST-based structural code search, lint, and rewrite via the `ast-grep` (`sg`) CLI. Use when a search or edit is about code SYNTAX STRUCTURE rather than text: finding every call site of a function, matching shapes such as "async functions without try/catch" or "useEffect without a dependency array", codemods that rewrite matched nodes, YAML lint rules that enforce project patterns, multi-pass symbol renaming, or listing a file's symbols, imports and exports. Also use whenever the request names ast-grep, sg, metavariables ($NAME, $$$ARGS), tree-sitter patterns, or sgconfig.yml. Use INSTEAD of grep/ripgrep whenever the pattern spans multiple lines, nests parentheses or brackets, or would otherwise match inside strings and comments. Covers 25+ languages (JS, TS, TSX, Python, Rust, Go, Java, C, C++, C#, Kotlin, Swift, Ruby, PHP and more). Prefer a sibling skill instead when the task is template/SQL/HTML/multi-format replacement or a Python 2 to 3 migration (use structural-refactor). Do NOT use for: plain string or regex searches, file-name lookups, log or config file searches, or a single edit in one known file.

We split this skill into the rules it gives an agent

7 rules. 0 are common, 2 are distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 20 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Check first: which ast-grep.

    line 43
  2. Very specific:

    Always put patterns in single quotes — double quotes let the shell expand $NAME first.

    line 104
  3. Very specific:

    Inspect: add --json=compact if you must verify match boundaries.

    line 118
  4. Very specific:

    Preview: add -r '<rewrite>' — the diff prints to stdout, nothing is written.

    line 119
  5. Very specific:

    Apply: add --interactive for per-match review, or -U to apply all.

    line 120
  6. Distinctive:

    Verify: run the search again and expect exit code 1 (no matches).

    line 121
  7. Distinctive:

    Read these on demand. Do not load them all at once.

    line 134

“Common” is measured: kept by at least 6 in 10 of the 20 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

ast-grep — Structural Code Search, Lint, and Rewrite

Content verified against ast-grep 0.45.1. Flags can drift between versions — when a command fails, check ast-grep <cmd> --help.

Overview

ast-grep is a fast, Rust-based CLI tool. It parses code with tree-sitter and matches the syntax tree, not the text. You write patterns that look like the code you search for. Metavariables ($NAME, $$$ARGS) act as wildcards for AST nodes.

Three main modes:

ModeCommandUse for
Search / rewriteast-grep run -p '<pattern>' (default command)One-time queries and codemods
Lintast-grep scanYAML rule sets, CI checks, complex rules
Exploreast-grep outlineSymbols, imports, exports of files

It supports 25+ languages: JavaScript, TypeScript, TSX, Python, Rust, Go, Java, C, C++, C#, Kotlin, Swift, Ruby, PHP, and more. See the language table in references/cli-reference.md.

Installation

Check first: which ast-grep. If it is not installed, run the bundled helper:

bash <SKILL_DIR>/scripts/install.sh

The script tries brew, cargo, npm, pip3, and MacPorts in order, and verifies the result. For manual installation see https://ast-grep.github.io/guide/quick-start.html.

Note: some systems have a different sg binary (shell group). Always use the full name ast-grep.

Tool Selection: grep vs ast-grep vs LSP

The question is about...Use
Text: strings, error messages, config values, file namesgrep / rg / fd
Syntax: "all calls that look like X", pattern rewrites, codemods, lint rulesast-grep
Semantics: go-to-definition, find-references across scopes, types, scope-aware renameLSP / compiler tooling
Graphs: transitive callers, circular imports, dead-code detection across a whole codebaseA graph script over ast-grep --json output; ast-grep alone sees only per-file matches

ast-grep matches syntax, not semantics. It cannot tell two same-named symbols in different scopes apart. A rename with ast-grep is an exact syntactic replace (it skips comments, strings, and oldNameHelper), but it hits every scope. For a true semantic rename, prefer an LSP rename; use ast-grep when no LSP is available and verify the diff.

There is no runtime conflict with LSP tools: the ast-grep CLI is stateless — it reads files, matches, and exits. It starts no server and builds no index.

Also do NOT use ast-grep when:

  • The pattern spans comments or string contents — patterns cannot match inside them.
  • The codebase is tiny (< 5 files) — just read the files.

Files with syntax errors are usually fine: tree-sitter error recovery still matches the valid regions.

Quick Start

# Find all console.log calls in TypeScript
ast-grep -p 'console.log($$$ARGS)' -l ts src/

# Rewrite: var -> const, interactive review per match
ast-grep -p 'var $N = $V' -r 'const $N = $V' -l js --interactive src/

# Apply all rewrites without confirmation
ast-grep -p '$P && $P()' -r '$P?.()' -l ts -U src/

# Only list files that contain a match
ast-grep -p 'eval($$$A)' -l js --files-with-matches src/

# JSON output for scripts (note: --json requires `=` for its value)
ast-grep -p 'function $NAME($$$P) { $$$B }' -l ts --json=compact src/ > matches.json

# Run one inline YAML rule without a file
ast-grep scan --inline-rules 'id: no-eval
language: typescript
severity: error
rule: {pattern: "eval($$$A)"}' src/

# Show the structure of a file
ast-grep outline src/parser.ts --type class,function

# Test a pattern without files, via stdin
echo 'var x = 1' | ast-grep -p 'var $N = $V' -l js --stdin

Always put patterns in single quotes — double quotes let the shell expand $NAME first. For interactive pattern experiments there is an online playground: https://ast-grep.github.io/playground.html

Metavariables — Minimal Reminder

  • $VAR matches exactly one AST node. $$$ARGS matches zero or more.
  • Default to $$$ for arguments, parameters, and bodies. foo($ARG) matches only one-argument calls — this is the most common cause of missed matches.
  • Repeated names must match identical content: $A == $A matches x == x, not x == y.
  • Names use A-Z, _, digits. $var is invalid. $_NAME is non-capturing.

Full syntax, pattern objects, strictness, and language pitfalls (TypeScript generics, keywords, statement-vs-expression): references/pattern-syntax.md.

Standard Workflow: Rewrite

  1. Search: ast-grep -p '<pattern>' -l <lang> <path> — check the matches.
  2. Inspect: add --json=compact if you must verify match boundaries.
  3. Preview: add -r '<rewrite>' — the diff prints to stdout, nothing is written.
  4. Apply: add --interactive for per-match review, or -U to apply all.
  5. Verify: run the search again and expect exit code 1 (no matches). Then run the project tests.

A rename needs multiple passes (definition, call sites, imports are distinct node kinds) — see references/pattern-syntax.md.

Exit Codes

  • run: 0 = at least one match, 1 = no match. In scripts, "no matches" is not an error.
  • scan: 0 = clean, 1 = diagnostics with error severity found. Use this as a CI gate.
  • Other non-zero codes signal usage or config errors (e.g. 2 bad flag, 8 invalid pattern/rule).
  • Pipelines mask exit codes. ast-grep ... | other-tool reports the last command's status. Set set -o pipefail (bash/zsh) when the ast-grep status matters.

Reference Files

Read these on demand. Do not load them all at once.

  • references/cli-reference.md — All subcommands and flags (verified against 0.45.1), flag syntax rules, language table.
  • references/pattern-syntax.md — Full pattern syntax, pattern objects, strictness levels, pitfalls with examples.
  • references/rule-yaml.md — YAML rule files, rule object (atomic/relational/composite), sgconfig.yml project setup, rule testing, CI.
  • references/pattern-cookbook.md — Ready-to-use patterns for JS/TS/Python, rewrite recipes with semantic warnings, task recipes (find callers, dead exports), YAML rule scenarios.

Bundled Scripts

Replace <SKILL_DIR> with the absolute directory of this SKILL.md file.

  • scripts/install.sh — Try available package managers in order and install ast-grep.
  • scripts/json-summary.py — Summarize ast-grep --json output: match counts per file plus a compact match list. Usage:

    set -o pipefail   # keep ast-grep's exit code visible
    ast-grep -p '<pattern>' --json=compact <path> | python3 <SKILL_DIR>/scripts/json-summary.py

Download now (ZIP)

  • Other versions20 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 20

    1. AprilNEA/OpenLogi★ 25ksame name
    2. ccusage/ccusage★ 19ksame name
    3. ryoppippi/ccusage★ 19ksame name
    4. warp-drive-data/warp-drive★ 3.2ksame name
    5. coleam00/skills★ 725same name
    6. nodetool-ai/nodetool★ 603same name
    7. moeru-ai/auv★ 198same name
    8. damusix/skills★ 61same name
    9. ulpi-io/browse★ 15same name
    10. tstapler/dotfiles★ 8same name

    10 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.

  • Used alongsideProjects with it also use rust, github-issues and 4 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.
    • MicrosoftSkill

      rust

      Use this guide when working on Rust changes in the FAST monorepo.

      Also in 3 projects that use this

    • SentrySkill

      github-issues

      Create, update, comment on, label, and inspect GitHub issues with concise, evidence-backed content. Use when users ask to open, edit, view, close, reopen, or triage GitHub issues — including tracking bugs, features, or tasks. Prefer this skill over generic repository tools for issue operations; do not use for pull requests, branches, pushes, or PR creation order questions.

      Also in 3 projects that use this

    • SentrySkill

      create-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

    • GoogleSkill

      tdd

      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

    • +2 more from getsentry
  • In this repository7 other files it gives its agents.

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.