Source profileQuality 94/100Review permissions

NousResearch/hermes-agent/optional-skills/software-development/ast-grep/SKILL.md

ast-grep

AST-aware structural code search and rewrite via ast-grep.

Source repository stars
235,927
Declared platforms
0
Static risk flags
1
Last source update
2026-08-25
Source checked
2026-08-25

Decision brief

What it does: where it fits

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 tex…

Best for

  • "Find every function that takes a Request parameter."
  • "Rewrite every console.log(x) to logger.info(x)."
  • "Strip every as any cast."

Not for

  • Tasks that require unconfirmed production actions or broad system permissions.
  • Environments where the pinned source and install steps cannot be inspected.

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeNot declaredNo explicit evidencePortability before use
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/NousResearch/hermes-agent --skill "optional-skills/software-development/ast-grep"
Safe inspection promptEditorial

Inspect the Agent Skill "ast-grep" from https://github.com/NousResearch/hermes-agent/blob/64a6f42cb38def7ad6524bdfe640a16997c88760/optional-skills/software-development/ast-grep/SKILL.md at commit 64a6f42cb38def7ad6524bdfe640a16997c88760. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    When to use this skill

    Use it whenever the question is about code structure, not bytes:

    "Find every function that takes a Request parameter.""Rewrite every console.log(x) to logger.info(x).""Strip every as any cast."
  2. 02

    Three things the agent must internalize

    The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently:

    The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently: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.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 refe…
  3. 03

    1. ast-grep is NOT regex

    The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently:

    The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently: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.
  4. 04

    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.

    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 refe…
  5. 05

    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:

    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:The helper does this automatically when you call replace --apply. Read references/pitfalls.md §9.

Permission review

Static risk signals and limitations

Runs scripts

medium · line 28

The documentation asks the agent to run terminal commands or scripts.

Run the helper and `sg` through the `terminal` tool. Single-quote every pattern so the shell never expands `$VAR`.

Runs scripts

medium · line 73

The documentation asks the agent to run terminal commands or scripts.

python scripts/ast_grep_helper.py search 'console.log($MSG)' --lang ts src/

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score94/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars235,927SourceRepository attention, not individual Skill quality
Compatibility0 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
NousResearch/hermes-agent
Skill path
optional-skills/software-development/ast-grep/SKILL.md
Commit
64a6f42cb38def7ad6524bdfe640a16997c88760
License
MIT
Collected
2026-08-25
Default branch
main
View the original SKILL.md

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 (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 Request parameter."
  • "Rewrite every console.log(x) to logger.info(x)."
  • "Strip every as any cast."
  • "Replace require(...) with import across the repo."
  • "Find empty catch blocks."
  • "Migrate Optional[X] to X | 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 sg through the terminal tool. Single-quote every pattern so the shell never expands $VAR.
  • For find→read chains around matches, use --json-out and process with execute_code rather than piping through interpreters.
  • This complements (does not replace) Hermes's patch tool: patch is 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 wroteWhat ast-grep sawWhat you wanted
foo|barbitwise-or of foo and barrun two separate searches
.*foonot parseable$$$ foo (if $$$ is a list of nodes) or use rg
\w+not parseable$VAR to capture any identifier
[a-z]character class, not parseableswitch 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 apply

The 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 like js, py, rs, kt accepted)
  • --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/ --apply

The 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.ps1

new 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-repo

If 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 --langsg 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 malformed.
  4. Check the AST of the target file: sg run -p '$_' --lang <lang> --debug-query=cst path/to/file | head -40 — find the kind you're trying to match.
  5. Try the playground: https://ast-grep.github.io/playground.html — paste code + pattern, see what's happening.

Do not blindly retry with variations. Each failure has a reason; surface it.


When to use YAML rules vs inline -p patterns

Use inline -p when:

  • One-off ad-hoc query.
  • The pattern is simple (no constraints, no fix template).
  • You're exploring.

Use YAML rules (file under rules/, run via sg scan) when:

  • The pattern is reused (lint rule, codemod that runs in CI).
  • You need constraints, transform, complex inside/has, or composite logic.
  • You want auto-fix (fix: field).
  • You want to test the rule (snapshot tests via sg test).

The full YAML rule schema is in references/yaml-rules.md. Project setup (sgconfig.yml, ruleDirs, utilDirs) is in references/sgconfig.md.


Output discipline

  • sg run --json=compact produces an array of match objects: { file, range: {start, end}, text, replacement?, lines, language, ... }.
  • Without --json, sg produces human-readable colored output suitable for terminals.
  • The helper's default output is human-readable (file:line:column + match preview). Pass --json-out for raw JSON.
  • The helper's replace always summarizes: number of matches, number of files, per-location preview.

When summarizing for the user, always include the count of files affected, not just the count of matches. Users care about blast radius.


Required reading (in order of priority)

  1. references/patterns.md — meta-variables, naming rules, strictness levels. Read when you're unsure why a pattern doesn't match.
  2. references/pitfalls.md — the failure-mode field guide. Read when 0 matches surprises you.
  3. references/recipes.md — copy-paste patterns by language. Read first when you start a new task.
  4. references/cli.mdsg run, sg scan, sg test, sg new, sg lsp. Read when the helper isn't enough.
  5. references/yaml-rules.md — YAML rule schema. Read when you outgrow inline patterns.
  6. references/sgconfig.md — project-level configuration. Read when you set up sg scan for a real project.
  7. references/install.md — per-OS install methods. Read only if install.sh / install.ps1 fail.

Invariants (do not break)

  • Validate before searching. When emitting a pattern programmatically, call helper validate first. It catches the regex-misuse class of mistakes that account for ~70% of "0 matches" debug sessions.
  • Dry-run before applying. Never run sg run -r ... --update-all without first inspecting the matches. The helper's replace enforces this by default.
  • Two-pass writes. When using sg directly to both preview and apply, run two invocations — --json ignores --update-all.
  • Single-quote patterns in shell. '$VAR' not "$VAR". The shell expands $VAR to the empty string in double quotes, breaking the pattern.
  • Pattern is code, not regex. When the pattern would need |, .*, \w, or [a-z], switch to search_files instead. Don't try to force ast-grep into a regex shape.
  • --lang is required for stdin. When piping with --stdin, set --lang explicitly; sg cannot infer from extension.
  • Linux: prefer ast-grep over sg because sg collides with setgroups from util-linux. The helper handles this; if you call sg directly, alias it: alias sg=ast-grep.

Frequently asked questions

What to verify before installation and use

What does the ast-grep source document cover?

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 tex…

How do I install ast-grep?

The source record exposes this install command: npx skills add https://github.com/NousResearch/hermes-agent --skill "optional-skills/software-development/ast-grep". Inspect the command and pinned source before running it.

Which permission-related actions were detected?

Static rules flagged exec-script in the source; the page lists the matching lines and excerpts.

Alternatives

Compare before choosing

Computed 10045,511

coreyhaines31/marketingskills

ab-testing

When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this," "which version is better," "test two versions," "statistical significance," "how long should I run this test," "growth experiments," "experiment velocity," "experiment backlog," "ICE score," "experimentation program

Computed 10029,034

garrytan/gbrain

bulk-ingestion

End-to-end discipline for turning any large data source (audio libraries, email takeouts, document corpora, chat exports, API dumps) into brain pages at scale. The lifecycle spine: SCHEMA → ACCESS → TRIAL → EVALUATE → IMPROVE → CODIFY → TEST → SKILLIFY → BULK → MONITOR. State is tracked in a durable JSON manifest (see MANIFEST-PATTERN.md) so any crash, session boundary, or subagent fan-out resumes from ground truth instead of memory.

Computed 10024,921

alirezarezvani/claude-skills

app-store-optimization

App Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklist

Computed 1005,241

dotnet/skills

migrate-vstest-to-mtp

Migrates .NET test projects from VSTest to Microsoft.Testing.Platform (MTP). Use when user asks to "migrate to MTP", "switch from VSTest", "enable Microsoft.Testing.Platform", "use MTP runner", set OutputType=Exe only for test projects in Directory.Build.props, or mentions EnableMSTestRunner, EnableNUnitRunner, or UseMicrosoftTestingPlatformRunner. USE FOR: MTP behavioral differences vs VSTest (exit code 8, zero tests discovered, --ignore-exit-code, TESTINGPLATFORM_EXITCODE_IGNORE); centralizing