betting-brain-v3 / rules
Cursor rule8 starsChanged 14 months agoMITView on GitHub
Code searchability patterns and ast-grep integration
- Installs packages
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository27 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- .cursor/rules/99-floor.mdcCursor rule
- .cursor/rules/ai-friendly-testing.mdcCursor rule
- .cursor/rules/analytics-stub-api.mdcCursor rule
- .cursor/rules/analytics-testing.mdcCursor rule
- .cursor/rules/api-patterns.mdcCursor rule
- .cursor/rules/browser-extension.mdcCursor rule
- .cursor/rules/bun-runtime.mdcCursor rule
- .cursor/rules/cache-optimization.mdcCursor rule
- .cursor/rules/ci-integration.mdcCursor rule
- .cursor/rules/ci-patterns.mdcCursor rule
- .cursor/rules/cloudflare-infrastructure.mdcCursor rule
- .cursor/rules/cloudflare-workers.mdcCursor rule
- .cursor/rules/coverage-thresholds.mdcCursor rule
- .cursor/rules/database-patterns.mdcCursor rule
- .cursor/rules/documentation.mdcCursor rule
- .cursor/rules/endpoint-routing.mdcCursor rule
- .cursor/rules/file-naming.mdcCursor rule
- .cursor/rules/mcp-integration.mdcCursor rule
- .cursor/rules/process-management.mdcCursor rule
- .cursor/rules/production-security.mdcCursor rule
- .cursor/rules/quality-standards.mdcCursor rule
- .cursor/rules/root-organization.mdcCursor rule
- .cursor/rules/security-patterns.mdcCursor rule
- .cursor/rules/testing.mdcCursor rule
- .cursor/rules/testing-patterns.mdcCursor rule
- .cursor/rules/test-setup-patterns.mdcCursor rule
The file
Show its rules and text
We split this code-searchability.mdc into the rules it gives an agent
16 rules. About 0 are common, 12 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈12
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 173
Rule: Never use string interpolation in SQL queries.
- Distinctive: line 188
Rule: All API responses must include CORS headers.
- Distinctive: line 210
Rule: All endpoint handlers must generate and use requestId.
- Distinctive: line 231
Rule: All logs should include requestId prefix.
- Very specific: line 271
Add rules to .ast-grep.yml:
- Distinctive: line 318
Search for "Run ast-grep"
- Distinctive: line 327
Run ast-grep scans before commits:
- Distinctive: line 338
Use ast-grep in PR reviews:
- Distinctive: line 349
Use ast-grep to find refactoring opportunities:
- Distinctive: line 361
Document searchable patterns in code:
- Very specific: line 419
Check syntax in .ast-grep.yml
- Distinctive: line 420
Verify language is set correctly
- Very specific: line 421
Test pattern in playground: https://ast-grep.github.io/playground.html
- Distinctive: line 425
Add more specific patterns
- Distinctive: line 427
Add paths to ignore list
- Very specific: line 435
[CURSOR_RULES.md](mdc:docs/CURSOR_RULES.md): - All Cursor rules
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
version: "1.0.0"
alwaysApply: true
description: "Code searchability patterns and ast-grep integration"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards"]
---
## Overview
This codebase uses **ast-grep** for structural code search and pattern matching. ast-grep provides semantic search beyond simple text matching, understanding TypeScript/JavaScript syntax.
See [sgconfig.yml](mdc:sgconfig.yml) and [rules/](mdc:rules/) for complete configuration.
## Quick Reference
### Common Search Commands
```bash
# Search for specific patterns
ast-grep --pattern 'async function $NAME' src/
sg -p 'const $VAR = fetch($$$)' src/
# Filter by specific rules
ast-grep scan --filter "sql-injection-risk"
sg scan --filter "unstructured-log"
# Scan all rules in project
ast-grep scan
sg scan
# Search in specific files
ast-grep --pattern 'throw Errors.$METHOD($$$)' src/api/
```
### Search by Feature
| Feature | Command | Location |
|---------|---------|----------|
| **SQL Injection** | `sg scan --filter "sql-injection-risk"` | All TS files |
| **CORS Missing** | `sg scan --filter "missing-cors-headers"` | All TS files |
| **Unstructured Logs** | `sg scan --filter "unstructured-log"` | All TS files |
| **Hardcoded URLs** | `sg scan --filter "hardcoded-url"` | All files |
| **WORKER_URL Dupe** | `sg scan --filter "worker-url-definition"` | Dashboard files |
## Installation
Install ast-grep globally:
```bash
# Using cargo (recommended)
cargo install ast-grep
# Using npm
npm install -g @ast-grep/cli
# Using brew (macOS)
brew install ast-grep
```
Verify installation:
```bash
sg --version
```
## Usage Patterns
### 1. Finding API Endpoints
```bash
# Find all endpoint handlers
ast-grep --pattern 'async function $NAME(request: Request, env: Env, requestId: string)' src/
# Find specific endpoint
sg -p 'async function getEvents' src/api/
# Find endpoints without requestId
sg scan --filter "missing-request-id"
```
**Example Output:**
```
src/api/routes.ts:45:1
async function getEvents(request: Request, env: Env, requestId: string): Promise<Response> {
// Implementation
}
```
### 2. Finding MCP Handlers
```bash
# Find all MCP tool handlers
ast-grep --pattern 'export async function $NAME(params: $PARAMS, env: Env): Promise<MCPToolResult>' src/mcp/
# Find specific handler
sg -p 'export async function getSteamMoves' src/
# Find handlers returning MCPToolResult
sg -p 'Promise<MCPToolResult>' src/
```
### 3. Finding Database Queries
```bash
# Find all D1 queries
ast-grep --pattern 'env.$DB.prepare($QUERY)' src/
# Find queries with specific table
sg -p "env.ANALYTICS.prepare(\`SELECT * FROM line_movements\`)" src/
# Find potential SQL injection risks
sg scan --filter "sql-injection-risk"
```
**Anti-Pattern Detection:**
```typescript
// ❌ BAD: String interpolation (detected by ast-grep)
env.ANALYTICS.prepare(`SELECT * FROM table WHERE id = '${id}'`);
// ✅ GOOD: Parameterized query
env.ANALYTICS.prepare(`SELECT * FROM table WHERE id = ?`).bind(id);
```
### 4. Finding Validation Calls
```bash
# Find all validation calls
ast-grep --pattern 'validateQueryParams($URL, $VALIDATORS)' src/
# Find specific validator
sg -p 'Validators.agentID' src/
sg -p 'validateQueryParams' src/
```
### 5. Finding Error Handling
```bash
# Find all error throws
ast-grep --pattern 'throw Errors.$METHOD($$$)' src/
# Find specific error type
sg -p 'throw Errors.validationError' src/
sg -p 'throw Errors.notFound' src/
```
### 6. Finding Console Logs
```bash
# Find all console logs
ast-grep --pattern 'console.$METHOD($$$)' src/
# Find unstructured logs (missing requestId)
sg scan --filter "unstructured-log"
sg scan --filter "unstructured-log" src/index.ts # Specific file
# Find specific log level
sg -p 'console.error' src/
```
## Code Quality Rules
### Security Rules
#### 1. SQL Injection Prevention
```bash
sg scan --filter "sql-injection-risk"
```
**Rule:** Never use string interpolation in SQL queries.
```typescript
// ❌ WRONG: SQL injection risk
const query = `SELECT * FROM users WHERE id = '${userId}'`;
// ✅ CORRECT: Parameterized query
const query = env.ANALYTICS.prepare(`SELECT * FROM users WHERE id = ?`).bind(userId);
```
#### 2. CORS Headers
```bash
sg scan --filter "missing-cors-headers"
```
**Rule:** All API responses must include CORS headers.
```typescript
// ❌ WRONG: Missing CORS
return new Response(JSON.stringify(data));
// ✅ CORRECT: With CORS
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
});
```
### Observability Rules
#### 1. Request ID Tracking
```bash
sg scan --filter "missing-request-id"
```
**Rule:** All endpoint handlers must generate and use requestId.
```typescript
// ❌ WRONG: Missing requestId
async function getEvents(request: Request, env: Env): Promise<Response> {
console.log('Fetching events');
// ...
}
// ✅ CORRECT: With requestId
async function getEvents(request: Request, env: Env, requestId: string): Promise<Response> {
console.log(`[${requestId}] Fetching events`);
// ...
}
```
#### 2. Structured Logging
```bash
sg scan --filter "unstructured-log"
```
**Rule:** All logs should include requestId prefix.
```typescript
// ❌ WRONG: Unstructured
console.log('Processing request');
// ✅ CORRECT: Structured
console.log(`[${requestId}] Processing request`);
```
## Dashboard Refactoring Patterns
### Finding Duplicate Code
```bash
# Find WORKER_URL definitions (should be 1, in shared/config.js)
sg scan --filter "worker-url-definition"
sg scan --filter "worker-url-definition" dashboards/ # Specific directory
# Find Chart.js usage
ast-grep --pattern 'new Chart($CTX, $$$)' dashboards/
# Find duplicate fetch calls
sg scan --filter "duplicate-fetch"
```
### Refactoring Checklist
- [ ] WORKER_URL moved to `dashboards/shared/config.js`
- [ ] Common functions moved to `dashboards/shared/utils.js`
- [ ] Styles moved to `dashboards/shared/styles.css`
- [ ] Chart helpers moved to `dashboards/shared/charts.js`
- [ ] All dashboards import from `shared/`
## Custom Patterns
### Creating Custom Rules
Add rules to `.ast-grep.yml`:
```yaml
rules:
- id: my-custom-rule
message: Custom pattern found
severity: warning
language: TypeScript
rule:
pattern: |
$YOUR_PATTERN_HERE
```
### Pattern Syntax
**Basic patterns:**
```yaml
pattern: const $VAR = $VALUE # Match any const declaration
pattern: async function $NAME($$$) # Match any async function
pattern: throw new Error($MSG) # Match error throws
```
**Meta-variables:**
- `$VAR` - Match single node
- `$$$` - Match multiple nodes (ellipsis)
- `$_` - Match anything, don't capture
**Combinators:**
```yaml
all: # All patterns must match
- pattern: async function $NAME
- pattern: await $CALL
any: # Any pattern matches
- pattern: console.log($$$)
- pattern: console.error($$$)
not: # Pattern must NOT match
pattern: requestId
```
## Integration with Cursor
ast-grep integrates seamlessly with Cursor for inline code search:
1. Open command palette (`Cmd+Shift+P`)
2. Search for "Run ast-grep"
3. Enter pattern: `async function $NAME`
4. Results appear in sidebar
## Best Practices
### 1. Regular Scans
Run ast-grep scans before commits:
```bash
# Add to pre-commit hook
sg scan --filter "sql-injection-risk"
sg scan --filter "unstructured-log"
sg scan --filter "missing-cors"
```
### 2. Code Reviews
Use ast-grep in PR reviews:
```bash
# Check for anti-patterns
sg scan --filter "sql-injection-risk"
sg scan --filter "missing-error-handling"
sg scan --filter "hardcoded-urls"
```
### 3. Refactoring
Use ast-grep to find refactoring opportunities:
```bash
# Find duplicate patterns
sg search 'const WORKER_URL = $URL'
# Find functions that can be extracted
sg search 'async function $NAME'
```
### 4. Documentation
Document searchable patterns in code:
```typescript
// @pattern: API endpoint handler
// @searchable: sg search 'async function getEvents'
async function getEvents(request: Request, env: Env, requestId: string): Promise<Response> {
// Implementation
}
```
## Common Searches
### Find All API Endpoints
```bash
ast-grep --pattern 'case "/$PATH":' src/
```
### Find All MCP Tools
```bash
sg -p 'tools/call' src/
```
### Find All Database Tables
```bash
ast-grep --pattern 'FROM $TABLE' src/
```
### Find All Validators
```bash
sg -p 'Validators.$METHOD' src/
```
### Find All Error Types
```bash
sg -p 'Errors.$TYPE' src/
```
## Troubleshooting
### ast-grep Not Found
```bash
# Install with cargo
cargo install ast-grep
# Or with npm
npm install -g @ast-grep/cli
```
### Rules Not Working
1. Check syntax in `.ast-grep.yml`
2. Verify language is set correctly
3. Test pattern in playground: https://ast-grep.github.io/playground.html
### Slow Performance
1. Add more specific patterns
2. Limit file extensions in config
3. Add paths to ignore list
## Related Documentation
- **[sgconfig.yml](mdc:sgconfig.yml)** - Project configuration
- **[rules/](mdc:rules/)** - Rule definitions
- **[CODE_QUALITY_AUDIT.md](mdc:docs/CODE_QUALITY_AUDIT.md)** - Code quality report
- **[CURSOR_RULES.md](mdc:docs/CURSOR_RULES.md)** - All Cursor rules
- **[ast-grep Documentation](https://ast-grep.github.io/)** - Official docs
**Status:** Production patterns established
**Last Updated:** 2025-10-07
## Quick Command Reference
```bash
# Pattern search
ast-grep --pattern 'PATTERN' PATH
sg -p 'PATTERN' PATH
# Rule scan (filter by ID)
sg scan --filter "RULE_ID"
sg scan --filter "RULE_ID" PATH
# Scan all rules
ast-grep scan
sg scan
```
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
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.

