ast-grep
shalomb/agent-skills/skills/ast-grep/SKILL.md
Use this skill for structural code search, analysis, and automated refactoring using AST patterns (via sg/ast-grep). Trigger this whenever the user asks to "find all usages of", "rename this pattern", "refactor all X to Y", "extract all functions that", or "lint for pattern". Prefer this over standard text search (grep) when the task requires understanding code structure, extracting function names/imports, or performing complex codebase-wide migrations.
What's in it
- ast-grep (sg)
- Quick patterns
- Pattern syntax
- Key flags (sg run)
- Rule YAML schema
- sgconfig.yml (project config)
- Common use cases
- JSON output schema
- Go SDK / vendored module search
---
name: ast-grep
description: Use this skill for structural code search, analysis, and automated refactoring using AST patterns (via sg/ast-grep). Trigger this whenever the user asks to "find all usages of", "rename this pattern", "refactor all X to Y", "extract all functions that", or "lint for pattern". Prefer this over standard text search (grep) when the task requires understanding code structure, extracting function names/imports, or performing complex codebase-wide migrations.
---
# ast-grep (sg)
Structural code search and rewriting using AST patterns. Think `grep` but matches syntax, not text. `$VAR` matches any single node; `$$$VARS` matches zero or more nodes.
## Quick patterns
```bash
# Search
sg run -p 'console.log($A)' -l js .
sg run -p 'def $FUNC($$$):' -l python .
# Rewrite (preview diff)
sg run -p 'var $V = $E' -r 'const $V = $E' -l js .
# Apply rewrite to all files
sg run -p 'var $V = $E' -r 'const $V = $E' -l js . --update-all
# JSON output for scripting
sg run -p '$FUNC($$$ARGS)' -l python . --json=stream
# Scan with a YAML rule file
sg scan -r rule.yml .
# Inline rule (no file)
sg scan --inline-rules '
id: no-var
language: javascript
rule:
pattern: var $V = $E
fix: const $V = $E
message: Use const
severity: warning
' .
```
## Pattern syntax
| Syntax | Matches |
|---|---|
| `$VAR` | Any single AST node (captures as metavariable) |
| `$$$VARS` | Zero or more nodes (ellipsis) |
| `$_` | Any node (anonymous, no capture) |
| Literal code | Exact structural match |
## Key flags (`sg run`)
| Flag | Purpose |
|---|---|
| `-p` | Pattern to match |
| `-r` | Replacement pattern (uses same `$VAR` names) |
| `-l` | Language (js, ts, py, python, go, rust, java, …) |
| `--json=stream` | One JSON object per match on stdout |
| `--json=pretty` | Pretty-printed JSON array |
| `--update-all` | Apply rewrite without confirmation |
| `--stdin` | Read code from stdin |
| `--files-with-matches` | Print only matching file paths |
| `-C <n>` | Show n lines of context |
| `--globs` | Restrict to file glob patterns |
## Rule YAML schema
```yaml
id: rule-id # required, unique
language: python # required
rule: # required — the matcher
pattern: $EXPR # atomic: match by pattern
# OR:
kind: function_definition # atomic: match by AST node type
regex: "^test_" # atomic: match by text regex
# Composites:
all: [rule1, rule2] # all must match
any: [rule1, rule2] # any must match
not: {pattern: $X} # negate
inside: {pattern: ...} # relational: node is inside this
has: {pattern: ...} # relational: node has descendant
follows: {pattern: ...} # relational: node follows this
precedes: {pattern: ...}# relational: node precedes this
fix: "replacement" # optional rewrite
message: "Human message" # optional lint message
severity: warning # hint | info | warning | error
```
## sgconfig.yml (project config)
```yaml
ruleDirs:
- rules/
testConfigs:
- testDir: tests/
```
Place at repo root. Run `sg scan .` to apply all rules.
## Common use cases
Load `references/ast-grep-patterns.md` for language-specific pattern examples and metavariable extraction recipes.
## JSON output schema
Each `--json=stream` line:
```json
{
"text": "matched text",
"file": "path/to/file.py",
"range": {"start": {"line": 0, "column": 0}, "end": {...}},
"metaVariables": {
"single": {"VAR": {"text": "captured", "range": {...}}},
"multi": {"VARS": [{"text": "...", "range": {...}}, ...]}
},
"language": "Python"
}
```
## Go SDK / vendored module search
Searching Go types in vendored dependencies or Go module cache:
```bash
# Find the cached module path
TYPES=$(find $(go env GOMODCACHE)/github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2* \
-name "types.go" -path "*/types/*")
# Search for a struct definition
sg -p 'type Action struct { $$$ }' "$TYPES"
# Search for a function in provider source
cd ~/projects/hashicorp/terraform-provider-aws
sg -p 'func expandListenerAction($$$) $$${ $$$ }' --lang go internal/service/elbv2/listener.go
```
More agent context in shalomb/agent-skills
86 other files this repository gives its agents, the first 60 shown.
AGENTS.md
Skill
- adrskills/adr/SKILL.md
- adzic-bddskills/adzic-bdd/SKILL.md
- agent-md-refactorskills/agent-md-refactor/SKILL.md
- agent-muxskills/agent-mux/SKILL.md
- agent-role-impersonatorskills/agent-role-impersonator/SKILL.md
- agilquest-reservationsskills/agilquest-reservations/SKILL.md
- ai-text-humanizerskills/ai-text-humanizer/SKILL.md
- architecture-decision-recordsskills/architecture-decision-records/SKILL.md
- atacskills/atac/SKILL.md
- aws-cliskills/aws-cli/SKILL.md
- bart-adversarial-reviewerskills/bart-adversarial-reviewer/SKILL.md
- bddskills/bdd/SKILL.md
- branch-doctorskills/branch-doctor/SKILL.md
- c4-architectureskills/c4-architecture/SKILL.md
- c4skills/c4/SKILL.md
- claude-sub-agentskills/claude-sub-agent/SKILL.md
- codemap-config-setupskills/codemap-config-setup/SKILL.md
- codemap-exploreskills/codemap-explore/SKILL.md
- codemap-handoffskills/codemap-handoff/SKILL.md
- codemap-hub-safetyskills/codemap-hub-safety/SKILL.md
- codemapskills/codemap/SKILL.md
- commitskills/commit/SKILL.md
- copilot-sub-agentskills/copilot-sub-agent/SKILL.md
- daily-standupskills/daily-standup/SKILL.md
- daily-statusskills/daily-status/SKILL.md
- debugskills/debug/SKILL.md
- design-thinkingskills/design-thinking/SKILL.md
- doctorskills/doctor/SKILL.md
- docx-word-processorskills/docx-word-processor/SKILL.md
- farley-tddskills/farley-tdd/SKILL.md
- forensicsskills/forensics/SKILL.md
- gemini-sub-agentskills/gemini-sub-agent/SKILL.md
- git-commit-formatterskills/git-commit-formatter/SKILL.md
- git-forensicsskills/git-forensics/SKILL.md
- github-actions-permissionsskills/github-actions-permissions/SKILL.md
- github-cliskills/github-cli/SKILL.md
- git-repo-discoveryskills/git-repo-discovery/SKILL.md
- git-safety-guardrailsskills/git-safety-guardrails/SKILL.md
- harness-idpskills/harness-idp/SKILL.md
- humanizeskills/humanize/SKILL.md
- iteration-plannerskills/iteration-planner/SKILL.md
- jira-issue-managerskills/jira-issue-manager/SKILL.md
- justfile-assistantskills/justfile-assistant/SKILL.md
- kiro-sub-agentskills/kiro-sub-agent/SKILL.md
- lessons-learnedskills/lessons-learned/SKILL.md
- lessonsskills/lessons/SKILL.md
- lisa-planning-agentskills/lisa-planning-agent/SKILL.md
- lovejoy-release-agentskills/lovejoy-release-agent/SKILL.md
- lsp-code-analysisskills/lsp-code-analysis/SKILL.md
- macro-to-microskills/macro-to-micro/SKILL.md
- marge-product-agentskills/marge-product-agent/SKILL.md
- meeting-notesskills/meeting-notes/SKILL.md
- mermaid-diagram-generatorskills/mermaid-diagram-generator/SKILL.md
- modern-cli-overridesskills/modern-cli-overrides/SKILL.md
- native-web-searchskills/native-web-search/SKILL.md
- obsidian-notetakerskills/obsidian-notetaker/SKILL.md
- outlook-headlessskills/outlook-headless/SKILL.md
- pdf-document-processorskills/pdf-document-processor/SKILL.md
- pi-sub-agentskills/pi-sub-agent/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
No reports yet. Be the first to say whether it worked.
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

