betting-brain-v3 / rules
Cursor rule8 starsChanged 14 months agoMITView on GitHub
Code quality standards and anti-pattern prevention
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,531 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/code-searchability.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/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
We split this production-security.mdc into the rules it gives an agent
2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 61
All patterns are enforced via ast-grep rules in the rules/ directory.
- Distinctive: line 206
Before deploying to production:
≈ “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 quality standards and anti-pattern prevention"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards", "security-patterns", "api-patterns", "bun-runtime", "database-patterns"]
---
# Production Security Patterns
**Metadata:**
- **Status:** ✅ Active
- **Always Apply:** true
- **Topics:** #security #production #scale
- **Last Updated:** 2025-10-07
## 🔍 Code Searchability Patterns
### Find security-patterns Issues with ast-grep
```bash
# Find parseFloat($$$)
# Find env.$DB.prepare(`SELECT $QUERY`)
# Find new Date()
# Find WASM.*exports
ast-grep --pattern 'parseFloat($$$)' src/
ast-grep --pattern 'env.$DB.prepare(`SELECT $QUERY`)' src/
ast-grep --pattern 'new Date()' src/
ast-grep --pattern 'WASM.*exports' src/
sg -p 'parseFloat($$$)' src/
sg -p 'env.$DB.prepare(`SELECT' src/
sg -p 'new' src/
sg -p 'WASM.*exports' src/
```
### security-patterns Discovery Commands
```bash
sg search "parseFloat" src/
sg search "SELECT" src/
sg search "new Date()" src/
sg search "WASM" src/
```
### Search Examples
```bash
# Find parseFloat usage (security risk)
sg search 'parseFloat($$$)' src/
# Find SQL injection risks
sg search 'env.$DB.prepare(`SELECT' src/
# Find timezone issues
sg search 'new' src/
# Find WASM memory leaks
sg search 'WASM.*exports' src/
```
## Overview
This rule enforces **production-ready security patterns** for sports betting platforms handling real money at scale.
All patterns are enforced via **ast-grep** rules in the `rules/` directory.
## Critical Security Rules
### 1. No parseFloat on Stakes (CRITICAL)
**Rule:** `rules/no-parsefloat-stake.yaml`
**Why:** `parseFloat("100abc")` returns `100`, accepting garbage input. For betting stakes, this is catastrophic.
```typescript
// ❌ DANGEROUS
const stake = parseFloat(userInput); // Accepts "100abc" → 100
// ✅ SAFE
const stake = Number(userInput);
if (isNaN(stake) || stake <= 0) {
throw Errors.validationError('Invalid stake amount');
}
```
**Enforcement:**
```bash
sg scan --filter "no-parsefloat-stake" --error
```
### 2. D1 SQL Injection Prevention (CRITICAL)
**Rule:** `rules/d1-sql-injection.yaml`
**Why:** Template literal interpolation bypasses D1's parameterization.
```typescript
// ❌ SQL INJECTION RISK
const userId = request.query.id;
await env.ANALYTICS.prepare(`SELECT * FROM users WHERE id = '${userId}'`).all();
// ✅ PARAMETERIZED QUERY
await env.ANALYTICS.prepare(`SELECT * FROM users WHERE id = ?`)
.bind(userId)
.all();
```
**Enforcement:**
```bash
sg scan --filter "d1-sql-injection" --error
```
### 3. Queue Batch Size Limits (HIGH)
**Rule:** `rules/queue-batch-limit.yaml`
**Why:** Cloudflare Queues enforce a hard limit of 100 messages per batch.
```typescript
// ❌ WILL FAIL at runtime
await env.QUEUE.send(items); // items.length > 100
// ✅ CORRECT: Batch in chunks
for (let i = 0; i < items.length; i += 100) {
const batch = items.slice(i, i + 100);
await env.QUEUE.send(batch);
}
```
**Enforcement:**
```bash
sg scan --filter "queue-batch-limit"
```
### 4. No new Date() in Edge Workers (MEDIUM)
**Rule:** `rules/no-new-date-edge.yaml`
**Why:** Edge workers run in UTC-only environments. Timezone ambiguity causes bugs.
```typescript
// ❌ WRONG: Timezone ambiguity
const now = new Date();
// ✅ CORRECT: Explicit UTC
const nowMs = Date.now();
const nowISO = new Date().toISOString();
```
**Enforcement:**
```bash
sg scan --filter "no-new-date-edge" --error
```
### 5. WASM Memory Management (HIGH)
**Rule:** `rules/wasm-memory-guard.yaml`
**Why:** WASM linear memory is not garbage collected. Memory leaks at the edge.
```typescript
// ❌ MEMORY LEAK
const result = wasmModule.instance.exports.calculate(ptr);
// ✅ SAFE: Always free in finally{}
let ptr;
try {
ptr = wasmModule.instance.exports.alloc(1024);
const result = wasmModule.instance.exports.calculate(ptr);
return result;
} finally {
if (ptr) wasmModule.instance.exports.free(ptr);
}
```
**Enforcement:**
```bash
sg scan --filter "wasm-memory-guard" --error
```
## CI/CD Integration
### Required Pre-Deployment Check
Add to `.github/workflows/deploy.yml`:
```yaml
- name: Security scan (ast-grep)
run: sg scan --error # Fail CI on security issues
```
### Pre-Commit Hook
```bash
#!/bin/sh
# .git/hooks/pre-commit
sg scan --filter "no-parsefloat-stake" --error
sg scan --filter "d1-sql-injection" --error
```
## Production Checklist
Before deploying to production:
- [ ] Run `sg scan --error` locally
- [ ] All critical rules pass (no-parsefloat-stake, d1-sql-injection)
- [ ] Input validation uses `Number()` not `parseFloat()`
- [ ] All D1 queries use `.bind()` parameterization
- [ ] Queue sends respect 100-message batch limit
- [ ] No `new Date()` without arguments in workers
- [ ] WASM memory freed in finally{} blocks
## Scale Testing
### Game-Day Load (1,000× normal traffic)
**Test scenario:**
- 1M req/min → Worker
- 10K bets/sec → D1
- 100K queue messages/sec
**Validation:**
```bash
# Load test with k6
bun run scripts/load-test.ts
# Monitor queue depth
wrangler queues list
# Check D1 latency
wrangler d1 execute betting-analytics --command "SELECT COUNT(*) FROM bets WHERE created_at > datetime('now', '-1 hour')"
```
## Related Documentation
- **[Production Patterns](../docs/PRODUCTION_PATTERNS.md)** - Complete guide
- **[ast-grep Quick Start](../docs/AST_GREP_QUICKSTART.md)** - Rule usage
- **[Security Audit](../docs/CODE_QUALITY_AUDIT.md)** - Code quality review
**Status:** Production-Ready
**Enforcement:** CI/CD Required
**Zero Tolerance:** SQL Injection, parseFloat on stakes
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.

