ast-grep – skill Lập trình cho agent AI
Tìm kiếm và viết lại code có nhận biết AST qua ast-grep.
Cài skill ast-grep bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/ast-grep-24015.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /ast-grep – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/ast-grep-24015.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $ast-grep – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/ast-grep-24015.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /ast-grep – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/ast-grep-24015.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /ast-grep – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
ast-grep
ast-grep (binary also named sg) is an AST-aware search and rewrite tool across 25 languages. It treats your pattern as code, parses it the same way it parses your project, and matches structurally. It is the right tool whenever your question depends on code shape rather than text bytes.
This skill ships a Python wrapper at scripts/ast_grep_helper.py and platform install scripts at install.sh (POSIX) and install.ps1 (Windows). The helper adds offline pattern validation, the two-pass write trick, and binary auto-resolution. Use it as your default entry point.
Upstream source: vendored from [code-yeongyu/ast-grep-skill](https://github.com/code-yeongyu/ast-grep-skill) (MIT), as shipped in oh-my-openagent's shared-skills bundle.
---
When to use this skill
Use it whenever the question is about code structure, not bytes:
- "Find every function that takes a
Requestparameter." - "Rewrite every
console.log(x)tologger.info(x)." - "Strip every
as anycast." - "Replace
require(...)withimportacross the repo." - "Find empty catch blocks."
- "Migrate
Optional[X]toX | None." - "Apply this codemod across these 200 files."
- "Run our YAML lint rules and surface violations."
Switch to search_files (or plain rg) when the question is text-shaped (string literal contents, comments, license headers, file names, cross-language regex). When in doubt, ask: "does the answer depend on the language's syntax tree, or just on the file's bytes?" If the former, ast-grep. If the latter, search_files.
Hermes integration notes:
- Run the helper and
sgthrough theterminaltool. Single-quote every pattern so the shell never expands$VAR. - For find→read chains around matches, use
--json-outand process withexecute_coderather than piping through interpreters. - This complements (does not replace) Hermes's
patchtool:patchis for targeted edits you author; ast-grep is for pattern-driven bulk rewrites across many sites.
---
Three things the agent must internalize
1. ast-grep is NOT regex
The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently:
| You wrote | What ast-grep saw | What you wanted |
|---|---|---|
| foo\|bar | bitwise-or of foo and bar | run two separate searches |
| .*foo | not parseable | $$$ foo (if $$$ is a list of nodes) or use rg |
| \w+ | not parseable | $VAR to capture any identifier |
| [a-z] | character class, not parseable | switch to rg |
The full anti-pattern table is in references/pitfalls.md §1. The helper's validate subcommand catches these mechanically — call it before debugging "no matches" by hand.
2. Patterns must be valid code
The pattern itself must parse. def $FN($$$): fails because the trailing : makes it incomplete; use def $FN($$$). function $NAME without params/body fails; use function $NAME($$$) { $$$ }. Full table per language in references/pitfalls.md §2.
3. --update-all and --json are mutually exclusive (silently)
This is the single biggest gotcha when scripting. sg run -p P -r R --json --update-all returns the JSON but does not mutate files. To both preview AND apply, run two passes:
sg run -p P -r R --json=compact . # pass 1: see what would change
sg run -p P -r R --update-all . # pass 2: actually applyThe helper does this automatically when you call replace --apply. Read references/pitfalls.md §9.
---
The helper script — scripts/ast_grep_helper.py
A single-file Python 3 stdlib wrapper. Same on every OS. The agent's default entry point.
search — find all matches of a pattern
python scripts/ast_grep_helper.py search 'console.log($MSG)' --lang ts src/Validates the pattern offline first. If the pattern looks like regex (\w, .*, |, etc.) the helper exits with a hint and never calls sg — saves a round-trip. Pass --force to skip validation.
Flags:
--lang ts(or any of the 25 languages; aliases likejs,py,rs,ktaccepted)--globs '!**/*.test.ts'(repeatable; prefix!to exclude)-C 3(context lines)--json-out(raw JSON instead of human format)
replace — rewrite by pattern, dry-run by default
# Dry-run preview (default — no files mutated)
python scripts/ast_grep_helper.py replace 'console.log($MSG)' 'logger.info($MSG)' --lang ts src/
# Actually apply
python scripts/ast_grep_helper.py replace 'console.log($MSG)' 'logger.info($MSG)' --lang ts src/ --applyThe helper:
1. Validates both pattern and rewrite for hint-detectable mistakes.
2. Runs pass 1 with --json=compact to collect matches and show a preview.
3. If --apply is set, runs pass 2 with --update-all to mutate files.
scan — run YAML rules
# Discover sgconfig.yml from cwd and run all rules
python scripts/ast_grep_helper.py scan src/
# Run a single rule file
python scripts/ast_grep_helper.py scan -r rules/no-console.yml src/
# Apply auto-fixes
python scripts/ast_grep_helper.py scan -U src/
# CI-friendly GitHub annotations
python scripts/ast_grep_helper.py scan --report-style short src/validate — offline pattern check (no sg call)
Useful for CI lints, pre-commit hooks, and quick sanity checks:
python scripts/ast_grep_helper.py validate '\w+' --lang ts
# → exit 2: regex \w not supported. Use $VAR for identifiers.
python scripts/ast_grep_helper.py validate 'console.log($MSG)' --lang ts
# → exit 0: pattern looks plausible for ast-grep.langs / doctor / install
python scripts/ast_grep_helper.py langs # list 25 supported languages and aliases
python scripts/ast_grep_helper.py doctor # check ast-grep binary availability
python scripts/ast_grep_helper.py install # delegate to install.sh / install.ps1new and test subcommands proxy directly to sg new and sg test.
---
Direct sg use (when the helper isn't enough)
The helper is opinionated. For full control, drop to sg. The skill ships a CLI cheat sheet in references/cli.md. The minimal idioms:
# Search
sg run -p 'console.log($MSG)' --lang ts src/
# Search with JSON for scripting
sg run -p 'console.log($MSG)' --lang ts --json=compact src/
# Rewrite, dry-run
sg run -p 'console.log($MSG)' -r 'logger.info($MSG)' --lang ts --json=compact src/
# Rewrite, apply
sg run -p 'console.log($MSG)' -r 'logger.info($MSG)' --lang ts --update-all src/
# Pattern from stdin (great for ad-hoc experiments)
echo 'console.log("hi")' | sg run -p 'console.log($MSG)' --lang js --stdin
# Debug a pattern that returns 0 matches
sg run -p '<your pattern>' --lang <lang> --debug-query=ast --stdin <<< '<sample-code>'
# Run YAML rules
sg scan src/
# Inline YAML rule (one-off)
sg scan --inline-rules '
id: no-todo
language: TypeScript
severity: warning
rule: { pattern: TODO }' src/When using sg directly in a shell, always single-quote patterns so $VAR is not expanded by the shell.
---
Decision tree — what to use, when
USER asks for "find/rewrite/codemod"
│
├─ structural pattern (function shape, call, class, import, control flow)
│ └→ ast-grep (this skill)
│
├─ text pattern (regex, alternation, character classes, file names)
│ └→ search_files / rg
│
├─ semantic question (what variable does this refer to? does this throw?)
│ └→ LSP tools, TypeScript compiler, Pyright, Semgrep with type inference
│
└─ multiple repos / federated search
└→ a search engine + then ast-grep / rg / LSP per-repoIf the user says "find all" or "every", default to ast-grep when the target is shaped (function, class, call, import, statement). Default to search_files when the target is text (string content, comment, license header, file name, identifier substring).
---
Always run dry-run first when rewriting
A bad pattern silently rewrites the wrong thing. The helper's replace defaults to dry-run for this reason. The flow is:
1. Search to confirm matches: helper search '<pattern>' --lang X .
2. Dry-run rewrite: helper replace '<pattern>' '<rewrite>' --lang X . (no --apply)
3. Inspect the dry-run summary: number of matches, files affected, the per-location preview.
4. If wrong: refine pattern, go back to step 1.
5. If right: helper replace '<pattern>' '<rewrite>' --lang X . --apply.
Never apply a rewrite that you have not first dry-run. After an --apply in a git repo, review with git diff --stat before committing.
---
When sg returns 0 matches but you know the code is there
In priority order:
1. Run helper validate '<pattern>' --lang <lang> — catches regex misuse, missing function bodies, Python trailing colons.
2. Check --lang — sg infers from extension; if you pass a .tsx file with --lang ts (not tsx), JSX won't parse.
3. Inspect the parsed pattern: sg run -p '<pattern>' --lang <lang> --debug-query=ast --stdin <<< '<sample>'. If it shows ERROR nodes, the pattern is
… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- ai-code-generation-guardrails – Dùng khi review code do AI tạo trước khi merge hoặc thực thi: lên kế hoạch kiểm tra AST…
- ai-coding-agent-guardrails – Bảo mật các AI coding agent (Claude Code, Cursor, Codex, Copilot) với ranh giới quyền…
- doubt-driven-development – Đưa mọi quyết định không tầm thường qua một đánh giá đối nghịch với ngữ cảnh mới trước…
- ai-loop – Chạy vòng lặp phát triển có giới hạn gồm spec-build-review, với phạm vi rõ ràng, điều…
- ai-native-cli – Đặc tả thiết kế gồm 98 quy tắc để xây dựng công cụ CLI mà AI agent có thể sử dụng an…
- code-review-excellence – Nắm vững các thực hành code review hiệu quả để đưa ra phản hồi mang tính xây dựng, phát…
- blackbox – Giao các tác vụ lập trình cho CLI đa mô hình Blackbox AI.
- git-workflow-and-versioning – Cấu trúc quy trình làm việc với git. Dùng khi thay đổi bất kỳ mã nguồn nào. Dùng khi…