
Code Structural Search
- 73 installs
- 36 repo stars
- Updated July 14, 2026
- oimiragieo/agent-studio
Helps with ai & agent building tasks.
About
code-structural-search is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- code-structural-search
- AI & Agent Building
- AI-coding skill
Code Structural Search by the numbers
- 73 all-time installs (skills.sh)
- +1 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #5,555 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/oimiragieo/agent-studio --skill code-structural-searchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 73 |
|---|---|
| repo stars | ★ 36 |
| Last updated | July 14, 2026 |
| Repository | oimiragieo/agent-studio ↗ |
What it does
Helps with ai & agent building tasks.
Files
Code Structural Search
Use ast-grep for AST-based code pattern matching.
When to Use
- Find code by structure, not keywords
- "Find all functions with 3 arguments"
- "Find all classes that extend X"
- "Find all database queries"
- "Find all error handling patterns"
- Precise code refactoring (change exact patterns)
Interface
Skill({ skill: 'code-structural-search', args: 'pattern-here --lang ts' });Language Support
ast-grep supports 20+ languages via tree-sitter:
| Language | Flag | File Extensions |
|---|---|---|
| JavaScript | --lang js | .js, .jsx |
| TypeScript | --lang ts | .ts, .tsx |
| Python | --lang py | .py, .pyi |
| Go | --lang go | .go |
| Rust | --lang rs | .rs |
| Java | --lang java | .java |
| C | --lang c | .c, .h |
| C++ | --lang cpp | .cpp, .cc, .hpp, .hh |
| C# | --lang cs | .cs |
| Kotlin | --lang kt | .kt, .kts |
| Swift | --lang swift | .swift |
| PHP | --lang php | .php |
| Ruby | --lang rb | .rb |
| Lua | --lang lua | .lua |
| Elixir | --lang ex | .ex, .exs |
| HTML | --lang html | .html, .htm |
| CSS | --lang css | .css |
| JSON | --lang json | .json |
| Bash | --lang bash | .sh, .bash |
| Thrift | --lang thrift | .thrift |
Pattern Examples
JavaScript/TypeScript
Find all functions:
function $NAME($ARGS) { $$ }Find functions with exactly 2 arguments:
function $NAME($A, $B) { $$ }Find async functions:
async function $NAME($ARGS) { $$ }Find class methods:
class $NAME {
$METHOD($ARGS) { $$ }
}Find arrow functions:
const $NAME = ($ARGS) => { $$ }Find console.log statements:
console.log($$$)Find try-catch blocks:
try { $$ } catch ($ERR) { $$ }Python
Find all functions:
def $NAME($ARGS): $$$Find class definitions:
class $NAME: $$$Find async functions:
async def $NAME($ARGS): $$$Find imports:
import $MODULEFind from imports:
from $MODULE import $$$Go
Find all functions:
func $NAME($ARGS) $RETURN { $$ }Find struct definitions:
type $NAME struct { $$$ }Find interface definitions:
type $NAME interface { $$$ }Rust
Find all functions:
fn $NAME($ARGS) -> $RETURN { $$ }Find impl blocks:
impl $NAME { $$$ }Find pub functions:
pub fn $NAME($ARGS) -> $RETURN { $$ }Java
Find all methods:
public $RETURN $NAME($ARGS) { $$ }Find class definitions:
public class $NAME { $$$ }Find interface definitions:
public interface $NAME { $$$ }Pattern Syntax
| Symbol | Meaning | Example |
|---|---|---|
$NAME | Single node/identifier | function $NAME() {} |
$$$ | Zero or more statements/nodes | class $NAME { $$$ } |
$$ | Zero or more statements (block) | if ($COND) { $$ } |
$_ | Anonymous wildcard (discard) | console.log($_) |
Performance
- Speed: <50ms per search (typical)
- Best combined with semantic search (Phase 1)
- Use ripgrep first for initial file discovery
vs Other Tools
vs Ripgrep (grep):
- Ripgrep: Fast text search, finds keywords
- ast-grep: Structural search, finds exact code patterns
- Use ripgrep first → then ast-grep to refine
vs Semantic Search (Phase 1):
- Semantic: Understands code meaning
- ast-grep: Understands code structure
- Combined: Best results (Phase 2)
Usage Workflow
1. Broad search with ripgrep:
Skill({ skill: 'ripgrep', args: 'authenticate --type ts' })2. Structural refinement with ast-grep:
Skill({ skill: 'code-structural-search', args: 'function authenticate($$$) { $$ } --lang ts' })3. Semantic understanding with Phase 1:
Skill({ skill: 'code-semantic-search', args: 'authentication logic' })Common Use Cases
Security Patterns
Find unvalidated inputs:
router.post($PATH, ($REQ, $RES) => { $$ })Find SQL queries (potential injection):
db.query(`SELECT * FROM ${$VAR}`)Find eval usage:
eval($$$)Code Quality Patterns
Find deeply nested functions:
function $NAME($ARGS) {
if ($COND) {
if ($COND2) {
if ($COND3) { $$ }
}
}
}Find long parameter lists (>5 params):
function $NAME($A, $B, $C, $D, $E, $F, $$$) { $$ }Find unused variables:
const $NAME = $VALUE;Refactoring Patterns
Find old API usage:
oldAPI.deprecatedMethod($$$)Find callback patterns (convert to async/await):
$FUNC($ARGS, ($ERR, $DATA) => { $$ })Find React class components (convert to hooks):
class $NAME extends React.Component { $$$ }Iron Laws
1. ALWAYS specify the language with `--lang` flag — without a language flag, ast-grep applies heuristics that produce false positives; specify --lang ts, --lang py, etc. for accurate AST parsing. 2. ALWAYS use ripgrep/keyword search first to narrow the target set — structural search over the whole codebase is slow; use ripgrep to find candidate files first, then apply ast-grep for precise matching. 3. NEVER use regex for structural code patterns — regex breaks on formatting differences, nested structures, and multi-line code; AST patterns are format-independent and semantically precise. 4. ALWAYS test patterns on a known match before running project-wide — patterns with incorrect syntax silently match nothing; verify the pattern finds at least one known example before broad application. 5. *ALWAYS use `$$$` for variable argument lists, not ` or .** — ast-grep uses metavariable syntax ($NAME, $$$, $$`); regex or glob syntax in patterns produces silent failures.
Anti-Patterns
| Anti-Pattern | Why It Fails | Correct Approach |
|---|---|---|
No --lang flag | Wrong parser applied; produces false positives and misses | Always specify --lang ts, --lang py, etc. |
| Running project-wide without ripgrep pre-filter | Slow on large codebases; many irrelevant results | Use ripgrep to identify candidate files first |
| Regex for structural matching | Breaks on multi-line, whitespace variations, nesting | Use ast-grep AST patterns ($NAME, $$$, etc.) |
| Untested pattern on full codebase | Incorrect patterns silently return nothing | Test on one known match first |
Using * or . for wildcards | Not valid ast-grep syntax; ignored or errors | Use $NAME for single node, $$$ for sequences |
Memory Protocol (MANDATORY)
Before starting: Read .claude/context/memory/learnings.md
After completing:
- New pattern →
.claude/context/memory/learnings.md - Issue found →
.claude/context/memory/issues.md - Decision made →
.claude/context/memory/decisions.md
ASSUME INTERRUPTION: If it's not in memory, it didn't happen.
Invoke the code-structural-search skill and follow it exactly as presented to you
'use strict';
/**
* Post-execute hook for code-structural-search
* Auto-generated by enterprise-bundle-scaffolder
*
* Records metrics after skill execution.
*/
function postExecute(_context) {
// Record execution metrics
return { ok: true, skill: 'code-structural-search' };
}
module.exports = { postExecute };
'use strict';
/**
* Pre-execute hook for code-structural-search
* Auto-generated by enterprise-bundle-scaffolder
*
* Validates inputs before skill execution.
*/
function preExecute(context) {
// Validate skill invocation context
if (!context || typeof context !== 'object') {
return { allow: true, message: 'code-structural-search: no context to validate' };
}
return { allow: true };
}
module.exports = { preExecute };
ast-grep Pattern Library
Comprehensive pattern reference for all supported languages.
Pattern Syntax Reference
| Symbol | Meaning | Example |
|---|---|---|
$NAME | Single identifier/node | function $NAME() {} |
$$$ | Zero or more statements/nodes | class $NAME { $$$ } |
$$ | Zero or more statements (block) | if ($COND) { $$ } |
$_ | Anonymous wildcard (discard) | console.log($_) |
$...REST | Rest parameters/arguments | function $NAME($...ARGS) { $$ } |
JavaScript/TypeScript Patterns
Functions
# All functions
sg -p 'function $NAME($$$) { $$ }' --lang js
# Async functions
sg -p 'async function $NAME($$$) { $$ }' --lang ts
# Arrow functions
sg -p 'const $NAME = ($$$) => { $$ }' --lang js
# Functions with exactly 3 parameters
sg -p 'function $NAME($A, $B, $C) { $$ }' --lang js
# Functions returning promises
sg -p 'function $NAME($$$): Promise<$TYPE> { $$ }' --lang ts
# Generator functions
sg -p 'function* $NAME($$$) { $$ }' --lang jsClasses
# All classes
sg -p 'class $NAME { $$$ }' --lang ts
# Classes extending another
sg -p 'class $NAME extends $BASE { $$$ }' --lang ts
# Classes implementing interface
sg -p 'class $NAME implements $INTERFACE { $$$ }' --lang ts
# Class constructors
sg -p 'constructor($$$) { $$ }' --lang ts
# Class methods
sg -p 'class $NAME { $METHOD($$$) { $$ } }' --lang ts
# Async class methods
sg -p 'async $METHOD($$$) { $$ }' --lang tsTypeScript Specifics
# Type definitions
sg -p 'type $NAME = $$$' --lang ts
# Interface definitions
sg -p 'interface $NAME { $$$ }' --lang ts
# Enum definitions
sg -p 'enum $NAME { $$$ }' --lang ts
# Generic functions
sg -p 'function $NAME<$TYPE>($$$) { $$ }' --lang ts
# Type assertions
sg -p '$VAR as $TYPE' --lang tsImports/Exports
# Named imports
sg -p 'import { $$$ } from $MODULE' --lang js
# Default imports
sg -p 'import $NAME from $MODULE' --lang js
# Named exports
sg -p 'export { $$$ }' --lang js
# Default exports
sg -p 'export default $$$' --lang js
# Re-exports
sg -p 'export * from $MODULE' --lang jsError Handling
# Try-catch blocks
sg -p 'try { $$ } catch ($ERR) { $$ }' --lang js
# Try-catch-finally
sg -p 'try { $$ } catch ($ERR) { $$ } finally { $$ }' --lang js
# Throw statements
sg -p 'throw new $ERROR($$$)' --lang jsAsync/Promises
# Promise chains
sg -p '$PROMISE.then($$$)' --lang js
# Async/await
sg -p 'await $PROMISE' --lang js
# Promise.all
sg -p 'Promise.all([$$$])' --lang jsReact Patterns
# Functional components
sg -p 'function $NAME($PROPS) { return $$$ }' --lang tsx
# React.FC components
sg -p 'const $NAME: React.FC<$PROPS> = ($$$) => { $$ }' --lang tsx
# useState hooks
sg -p 'const [$STATE, $SETTER] = useState($$$)' --lang tsx
# useEffect hooks
sg -p 'useEffect(() => { $$ }, [$$$])' --lang tsx
# Class components
sg -p 'class $NAME extends React.Component { $$$ }' --lang tsx
# Component props destructuring
sg -p 'function $NAME({ $$$ }) { $$ }' --lang tsxPython Patterns
Functions
# All functions
sg -p 'def $NAME($$$): $$$' --lang py
# Async functions
sg -p 'async def $NAME($$$): $$$' --lang py
# Functions with decorators
sg -p '@$DECORATOR\ndef $NAME($$$): $$$' --lang py
# Functions with type hints
sg -p 'def $NAME($ARGS) -> $RETURN: $$$' --lang py
# Lambda functions
sg -p 'lambda $ARGS: $$$' --lang pyClasses
# All classes
sg -p 'class $NAME: $$$' --lang py
# Classes with inheritance
sg -p 'class $NAME($BASE): $$$' --lang py
# Classes with metaclass
sg -p 'class $NAME(metaclass=$META): $$$' --lang py
# __init__ methods
sg -p 'def __init__(self, $$$): $$$' --lang py
# Class methods
sg -p '@classmethod\ndef $NAME($$$): $$$' --lang py
# Static methods
sg -p '@staticmethod\ndef $NAME($$$): $$$' --lang pyImports
# Import statements
sg -p 'import $MODULE' --lang py
# From imports
sg -p 'from $MODULE import $$$' --lang py
# Relative imports
sg -p 'from .$MODULE import $$$' --lang py
# Import aliases
sg -p 'import $MODULE as $ALIAS' --lang pyError Handling
# Try-except blocks
sg -p 'try: $$$\nexcept $EXC: $$$' --lang py
# Try-except-finally
sg -p 'try: $$$\nexcept $EXC: $$$\nfinally: $$$' --lang py
# Raise statements
sg -p 'raise $EXCEPTION($$$)' --lang pyContext Managers
# With statements
sg -p 'with $CONTEXT as $VAR: $$$' --lang py
# Multiple contexts
sg -p 'with $CTX1 as $VAR1, $CTX2 as $VAR2: $$$' --lang pyComprehensions
# List comprehensions
sg -p '[$EXPR for $VAR in $ITER]' --lang py
# Dict comprehensions
sg -p '{$KEY: $VALUE for $VAR in $ITER}' --lang py
# Generator expressions
sg -p '($EXPR for $VAR in $ITER)' --lang pyGo Patterns
Functions
# All functions
sg -p 'func $NAME($$$) $RETURN { $$ }' --lang go
# Methods
sg -p 'func ($RECV $TYPE) $NAME($$$) $RETURN { $$ }' --lang go
# Variadic functions
sg -p 'func $NAME($ARGS ...$TYPE) { $$ }' --lang go
# Functions with named returns
sg -p 'func $NAME($$$) (result $TYPE) { $$ }' --lang goTypes
# Struct definitions
sg -p 'type $NAME struct { $$$ }' --lang go
# Interface definitions
sg -p 'type $NAME interface { $$$ }' --lang go
# Type aliases
sg -p 'type $NAME $TYPE' --lang goError Handling
# If err != nil pattern
sg -p 'if err != nil { $$ }' --lang go
# Error returns
sg -p 'return $$$, err' --lang goGoroutines
# Go statements
sg -p 'go $FUNC($$$)' --lang go
# Go anonymous functions
sg -p 'go func($$$) { $$ }($$$)' --lang goChannels
# Channel creation
sg -p 'make(chan $TYPE)' --lang go
# Channel send
sg -p '$CHAN <- $VALUE' --lang go
# Channel receive
sg -p '$VALUE := <-$CHAN' --lang go
# Select statements
sg -p 'select { $$$ }' --lang goRust Patterns
Functions
# All functions
sg -p 'fn $NAME($$$) -> $RETURN { $$ }' --lang rs
# Public functions
sg -p 'pub fn $NAME($$$) -> $RETURN { $$ }' --lang rs
# Async functions
sg -p 'async fn $NAME($$$) -> $RETURN { $$ }' --lang rs
# Unsafe functions
sg -p 'unsafe fn $NAME($$$) { $$ }' --lang rsStructs & Impls
# Struct definitions
sg -p 'struct $NAME { $$$ }' --lang rs
# Impl blocks
sg -p 'impl $NAME { $$$ }' --lang rs
# Trait impls
sg -p 'impl $TRAIT for $TYPE { $$$ }' --lang rsError Handling
# Match expressions
sg -p 'match $EXPR { $$$ }' --lang rs
# Result unwrap
sg -p '$EXPR.unwrap()' --lang rs
# Question mark operator
sg -p '$EXPR?' --lang rs
# If let pattern
sg -p 'if let $PATTERN = $EXPR { $$ }' --lang rsMemory Safety
# Unsafe blocks
sg -p 'unsafe { $$ }' --lang rs
# Raw pointers
sg -p '*const $TYPE' --lang rs
sg -p '*mut $TYPE' --lang rsJava Patterns
Classes & Methods
# Public classes
sg -p 'public class $NAME { $$$ }' --lang java
# Public methods
sg -p 'public $RETURN $NAME($$$) { $$ }' --lang java
# Static methods
sg -p 'public static $RETURN $NAME($$$) { $$ }' --lang java
# Abstract methods
sg -p 'abstract $RETURN $NAME($$$);' --lang javaInterfaces
# Interface definitions
sg -p 'public interface $NAME { $$$ }' --lang java
# Classes implementing interfaces
sg -p 'public class $NAME implements $INTERFACE { $$$ }' --lang javaError Handling
# Try-catch blocks
sg -p 'try { $$ } catch ($EXC $VAR) { $$ }' --lang java
# Try-with-resources
sg -p 'try ($RESOURCE) { $$ }' --lang java
# Throw statements
sg -p 'throw new $EXCEPTION($$$)' --lang javaSecurity Patterns (Cross-Language)
SQL Injection
# JavaScript string template SQL (vulnerable)
sg -p 'db.query(`SELECT * FROM ${$VAR}`)' --lang js
# Python string format SQL (vulnerable)
sg -p 'cursor.execute(f"SELECT * FROM {$VAR}")' --lang pyCommand Injection
# JavaScript exec (vulnerable)
sg -p 'exec($CMD)' --lang js
# Python os.system (vulnerable)
sg -p 'os.system($CMD)' --lang pyXSS
# JavaScript innerHTML (vulnerable)
sg -p '$ELEM.innerHTML = $DATA' --lang js
# Dangerously set HTML in React
sg -p 'dangerouslySetInnerHTML={{ __html: $DATA }}' --lang tsxAuthentication
# Missing authentication checks
sg -p 'router.post($PATH, ($REQ, $RES) => { $$ })' --lang js
# Find auth middleware usage
sg -p 'router.post($PATH, authenticate, ($REQ, $RES) => { $$ })' --lang jsCode Quality Patterns
Complexity
# Deeply nested if statements (>3 levels)
sg -p 'if ($COND1) { if ($COND2) { if ($COND3) { if ($COND4) { $$ } } } }' --lang js
# Long parameter lists (>5 params)
sg -p 'function $NAME($A, $B, $C, $D, $E, $F, $$$) { $$ }' --lang jsDead Code
# Unused variables (require manual verification)
sg -p 'const $NAME = $VALUE;' --lang js
# Console.log statements (cleanup before production)
sg -p 'console.log($$$)' --lang js
# Debugger statements
sg -p 'debugger' --lang jsDeprecated APIs
# Find old API usage
sg -p 'oldAPI.deprecatedMethod($$$)' --lang js
# Find callback patterns (convert to async/await)
sg -p '$FUNC($ARGS, ($ERR, $DATA) => { $$ })' --lang jsUsage Tips
Combining Patterns
Use multiple patterns for complex searches:
# Find all async functions with try-catch
sg -p 'async function $NAME($$$) { try { $$ } catch { $$ } }' --lang js
# Find classes with specific method
sg -p 'class $NAME { authenticate($$$) { $$ } }' --lang tsOutput Formats
# JSON output for parsing
sg -p '$PATTERN' --lang js --json
# Show context lines
sg -p '$PATTERN' --lang js -A 3 -B 3
# Only show matches (no filenames)
sg -p '$PATTERN' --lang js --heading=neverPerformance
# Search specific directory
sg -p '$PATTERN' --lang js src/
# Exclude directories
sg -p '$PATTERN' --lang js --no-ignore tests/
# Parallel search (faster for large codebases)
sg -p '$PATTERN' --lang js --threads 4Common Workflows
1. Security Audit
# Step 1: Find all routes
sg -p 'router.$METHOD($PATH, $$$)' --lang js
# Step 2: Find routes without auth
sg -p 'router.$METHOD($PATH, ($REQ, $RES) => { $$ })' --lang js
# Step 3: Find SQL queries
sg -p 'db.query($$$)' --lang js2. Refactoring
# Step 1: Find old pattern
sg -p 'oldAPI.method($$$)' --lang js
# Step 2: Replace with new pattern (manual or scripted)
# oldAPI.method() → newAPI.method()3. Code Review
# Step 1: Find functions without error handling
sg -p 'function $NAME($$$) { $$ }' --lang js | grep -v 'try'
# Step 2: Find long functions (>50 lines - manual count)
sg -p 'function $NAME($$$) { $$ }' --lang js
# Step 3: Find complex conditionals
sg -p 'if ($COND1 && $COND2 && $COND3 && $COND4) { $$ }' --lang jsMemory Protocol (MANDATORY)
Before starting: Read .claude/context/memory/learnings.md
After completing:
- New pattern →
.claude/context/memory/learnings.md - Issue found →
.claude/context/memory/issues.md - Decision made →
.claude/context/memory/decisions.md
ASSUME INTERRUPTION: If it's not in memory, it didn't happen.
Code Structural Search - README
Overview
The code-structural-search skill provides AST-based code pattern matching using ast-grep, a fast structural search and replace tool.
Key Benefits:
- Structure-aware: Matches code patterns, not just text
- Fast: <50ms typical search time
- Multi-language: 20+ languages via tree-sitter
- Precise: Find exact code patterns for refactoring
Installation
Option A: npm (Recommended)
npm install -g @ast-grep/cliOption B: Cargo (if Rust available)
cargo install ast-grepVerify Installation
ast-grep --version
# or
sg --versionQuick Start
1. Basic Search
Find all functions in TypeScript:
sg -p 'function $NAME($$$) { $$ }' --lang ts2. Find Security Issues
Find unvalidated SQL queries:
sg -p 'db.query(`SELECT * FROM ${$VAR}`)' --lang js3. Refactoring Support
Find old API usage:
sg -p 'oldAPI.deprecatedMethod($$$)' --lang jsPattern Syntax
| Symbol | Meaning | Example |
|---|---|---|
$NAME | Single node/identifier | function $NAME() {} |
$$$ | Zero or more statements/nodes | class $NAME { $$$ } |
$$ | Zero or more statements (block) | if ($COND) { $$ } |
$_ | Anonymous wildcard (discard) | console.log($_) |
Supported Languages
| Language | Flag | Extensions |
|---|---|---|
| JavaScript | --lang js | .js, .jsx |
| TypeScript | --lang ts | .ts, .tsx |
| Python | --lang py | .py, .pyi |
| Go | --lang go | .go |
| Rust | --lang rs | .rs |
| Java | --lang java | .java |
| C | --lang c | .c, .h |
| C++ | --lang cpp | .cpp, .cc, .hpp |
| C# | --lang cs | .cs |
Full language support: See PATTERNS.md for complete list.
Common Use Cases
1. Find All Async Functions
sg -p 'async function $NAME($$$) { $$ }' --lang ts2. Find Classes Extending a Base
sg -p 'class $NAME extends React.Component { $$$ }' --lang tsx3. Find Error Handling Gaps
sg -p 'function $NAME($$$) { $$ }' --lang js | grep -v 'try'4. Find Deprecated Patterns
sg -p 'oldAPI.method($$$)' --lang js5. Security Audit
Find SQL injection risks:
sg -p 'db.query(`$$$${$VAR}$$$`)' --lang jsFind XSS risks:
sg -p '$ELEM.innerHTML = $DATA' --lang jsIntegration with Agent-Studio
From Skills
// Use the skill
Skill({ skill: 'code-structural-search', args: 'function authenticate($$$) { $$ } --lang ts' });From CLI
# Run directly
ast-grep -p 'pattern-here' --lang ts
# or with short name
sg -p 'pattern-here' --lang tsWorkflow Integration
Combine with other skills for best results:
1. Broad search (ripgrep):
Skill({ skill: 'ripgrep', args: 'authenticate --type ts' });2. Structural refinement (ast-grep):
Skill({ skill: 'code-structural-search', args: 'function authenticate($$$) { $$ } --lang ts' });3. Semantic understanding (Phase 1):
Skill({ skill: 'code-semantic-search', args: 'authentication logic' });Output Formats
Default (Human-Readable)
sg -p 'function $NAME() {}' --lang js
# Shows filename, line number, matched codeJSON (Machine-Parsable)
sg -p 'function $NAME() {}' --lang js --json
# Returns structured JSON for parsingWith Context
sg -p 'function $NAME() {}' --lang js -A 3 -B 3
# Shows 3 lines before and after each matchPerformance Tips
1. Use Specific Language Flags
# GOOD - Fast, precise
sg -p '$PATTERN' --lang ts
# BAD - Slow, tries all languages
sg -p '$PATTERN'2. Search Specific Directories
# GOOD - Focused search
sg -p '$PATTERN' --lang ts src/
# BAD - Searches entire project
sg -p '$PATTERN' --lang ts3. Exclude Irrelevant Directories
# Skip node_modules, dist, etc.
sg -p '$PATTERN' --lang ts --no-ignore tests/4. Use Parallel Threads (Large Codebases)
sg -p '$PATTERN' --lang ts --threads 4Common Patterns Reference
JavaScript/TypeScript
# All functions
sg -p 'function $NAME($$$) { $$ }' --lang js
# Async functions
sg -p 'async function $NAME($$$) { $$ }' --lang ts
# Arrow functions
sg -p 'const $NAME = ($$$) => { $$ }' --lang js
# Classes
sg -p 'class $NAME { $$$ }' --lang ts
# React components
sg -p 'function $NAME($PROPS) { return $$$ }' --lang tsxPython
# All functions
sg -p 'def $NAME($$$): $$$' --lang py
# Async functions
sg -p 'async def $NAME($$$): $$$' --lang py
# Classes
sg -p 'class $NAME: $$$' --lang pyGo
# All functions
sg -p 'func $NAME($$$) $RETURN { $$ }' --lang go
# Structs
sg -p 'type $NAME struct { $$$ }' --lang goRust
# All functions
sg -p 'fn $NAME($$$) -> $RETURN { $$ }' --lang rs
# Impl blocks
sg -p 'impl $NAME { $$$ }' --lang rsTroubleshooting
Issue: "command not found: sg"
Solution:
1. Check installation: npm list -g @ast-grep/cli 2. Verify PATH includes npm global bin directory 3. Try full command: npx @ast-grep/cli (if npm install local)
Issue: "Pattern not matching expected code"
Solution:
1. Verify language flag is correct (--lang ts for TypeScript) 2. Check pattern syntax matches AST structure (not text) 3. Use --debug-query to see AST representation
Issue: "Too many results"
Solution:
1. Make pattern more specific (use more metavariables) 2. Search specific directory: sg -p '$PATTERN' --lang ts src/ 3. Exclude directories: sg -p '$PATTERN' --lang ts --no-ignore tests/
Issue: "Performance is slow"
Solution:
1. Add language flag: --lang ts (don't make ast-grep guess) 2. Search specific directory: sg -p '$PATTERN' --lang ts src/ 3. Use parallel threads: --threads 4 4. Exclude large directories (node_modules, dist)
Advanced Features
1. Rewrite Mode (Find and Replace)
sg -p 'oldAPI.method($$$)' -r 'newAPI.method($$$)' --lang js2. Interactive Mode
sg -p '$PATTERN' --lang ts --interactive
# Shows matches one by one, confirm each replacement3. Rule Files (Complex Searches)
Create .ast-grep/rules/security.yml:
id: no-sql-injection
language: js
rule:
pattern: db.query(`SELECT * FROM ${$VAR}`)
message: Potential SQL injection vulnerability
severity: errorRun with:
sg scan4. Combining Patterns (AND logic)
rule:
all:
- pattern: function $NAME($$$) { $$ }
- not:
pattern: try { $$ } catch { $$ }Documentation
- SKILL.md: Quick reference for skill usage
- PATTERNS.md: Comprehensive pattern library (all languages)
- README.md: This file (setup, usage, troubleshooting)
Related Skills
- ripgrep: Fast text-based search (use first for broad filtering)
- code-semantic-search: Semantic understanding (Phase 1)
- code-hybrid-search: Combined semantic + structural (Phase 2)
External Resources
- Official docs: https://ast-grep.github.io/
- Pattern guide: https://ast-grep.github.io/guide/rule-config.html
- GitHub: https://github.com/ast-grep/ast-grep
- Playground: https://ast-grep.github.io/playground.html
Memory Protocol (MANDATORY)
Before starting: Read .claude/context/memory/learnings.md
After completing:
- New pattern →
.claude/context/memory/learnings.md - Issue found →
.claude/context/memory/issues.md - Decision made →
.claude/context/memory/decisions.md
ASSUME INTERRUPTION: If it's not in memory, it didn't happen.
code-structural-search Research Requirements
Generated: 2026-02-28
Skill Description
Use ast-grep for AST-based code pattern matching.
Research Areas
- Current best practices for code-structural-search
- Industry standards and tooling
- Integration patterns
Source References
- To be populated by skill-updater research phase
code-structural-search Rules
Purpose
Use ast-grep for AST-based code pattern matching.
Best Practices
- Follow established patterns
- Validate inputs at boundaries
Integration Points
See SKILL.md for complete documentation.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "code-structural-searchInput",
"description": "Input schema for Use ast-grep for AST-based code pattern matching.",
"type": "object",
"additionalProperties": true,
"properties": {
"target": {
"type": "string",
"description": "Target file or path for the skill to operate on"
},
"options": {
"type": "object",
"description": "Additional options for skill execution",
"additionalProperties": true
}
}
}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "code-structural-searchOutput",
"type": "object",
"additionalProperties": true,
"properties": {
"ok": {
"type": "boolean"
},
"summary": {
"type": "string"
}
}
}
#!/usr/bin/env node
'use strict';
/**
* code-structural-search - Enterprise Skill Script
* Auto-generated by enterprise-bundle-scaffolder
*/
const fs = require('fs');
const path = require('path');
// Parse arguments
const args = process.argv.slice(2);
const options = {};
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const key = args[i].slice(2);
const value = args[i + 1] && !args[i + 1].startsWith('--') ? args[++i] : true;
options[key] = value;
}
}
if (options.help) {
console.log(`
code-structural-search - Enterprise Skill
Usage:
node main.cjs --check <file> Check a file against guidelines
node main.cjs --list List all guidelines
node main.cjs --help Show this help
Description:
Use ast-grep for AST-based code pattern matching.
`);
process.exit(0);
}
if (options.list) {
console.log('Guidelines for code-structural-search:');
console.log('See SKILL.md for full guidelines');
process.exit(0);
}
console.log('code-structural-search skill loaded. Use with Claude for code review.');
code-structural-search Implementation Template
Goal
- Define target outcome and acceptance criteria.
TDD
1. Red 2. Green 3. Refactor
Verification
- lint
- format
- targeted tests