The GitHub Pages site has the complete documentation with syntax highlighting, navigation, and visual examples.
The definitive starting point for Claude Code projects. Based on Claude Code Mastery Guides V1-V5 by TheDecipherist.
This is a ready-to-use project template that bakes in every best practice from the Claude Code Mastery Guide series (V1, V2, V3, V4, and V5). Instead of reading 4,000+ lines of guides and setting things up yourself, clone this and start building.
Clone → /setup → /diagram all → hooks firing on file edit → /review catching issues
Everything you need to start a Claude Code project the right way — security, automation, documentation, and testing all pre-configured.
- CLAUDE.md — Battle-tested project instructions with 11 numbered critical rules for security, TypeScript, database wrappers, testing, and deployment
- Global CLAUDE.md — Security gatekeeper for all projects. Never publish secrets, never commit .env files, standardized scaffolding rules
- 16 Slash Commands —
/install-global,/setup,/diagram,/review,/commit,/progress,/test-plan,/architecture,/new-project,/security-check,/optimize-docker,/create-e2e,/create-api,/worktree,/what-is-my-ai-doing,/refactor - Hooks — Deterministic enforcement that always runs. Block secrets, lint on save, verify no credentials in staged commits
- Skills — Context-aware templates: systematic code review checklist and full microservice scaffolding
- Custom Agents — Read-only code reviewer for security audits. Test writer that creates tests with explicit assertions
- Documentation Templates — Pre-structured ARCHITECTURE.md, INFRASTRUCTURE.md, and DECISIONS.md templates
- Testing Templates — Master test checklist, issue tracking log, and a singleton database wrapper that prevents connection pool explosion
- Live AI Monitor — See every tool call, token, cost, and violation in real-time with
/what-is-my-ai-doing. Zero token overhead
# Clone the starter kit
git clone https://github.com/TheDecipherist/claude-code-mastery-project-starter-kit my-project
cd my-project
# Remove git history and start fresh
rm -rf .git
git init
# Copy your .env
cp .env.example .env# Run the install command — smart merges into existing config
/install-globalThis installs global CLAUDE.md rules, settings.json hooks, and enforcement scripts (block-secrets.py, verify-no-secrets.sh, rulecatch-check.sh) into ~/.claude/. If you already have a global config, it merges without overwriting.
Manual setup (if you prefer)
cp global-claude-md/CLAUDE.md ~/.claude/CLAUDE.md
cp global-claude-md/settings.json ~/.claude/settings.json
mkdir -p ~/.claude/hooks
cp .claude/hooks/block-secrets.py ~/.claude/hooks/
cp .claude/hooks/verify-no-secrets.sh ~/.claude/hooks/
cp .claude/hooks/rulecatch-check.sh ~/.claude/hooks/- Run
/setup— Interactive .env configuration (database, GitHub, Docker, analytics) - Edit
CLAUDE.md— Update port assignments, add your specific rules - Run
/diagram all— Auto-generate architecture, API, database, and infrastructure diagrams - Edit
CLAUDE.local.md— Add your personal preferences
The database wrapper (src/core/db/index.ts) works out of the box — just set DATABASE_URL in your .env and it connects to MongoDB automatically. All query inputs are auto-sanitized against NoSQL injection (configurable via DB_SANITIZE_INPUTS=false or sanitize = false in conf).
claudeThat's it. Claude Code now has battle-tested rules, deterministic hooks, slash commands, and documentation templates all ready to go.
project/
├── CLAUDE.md # Project instructions (customize this!)
├── CLAUDE.local.md # Personal overrides (gitignored)
├── .claude/
│ ├── settings.json # Hooks configuration
│ ├── commands/
│ │ ├── review.md # /review — code review
│ │ ├── commit.md # /commit — smart commit
│ │ ├── progress.md # /progress — project status
│ │ ├── test-plan.md # /test-plan — generate test plan
│ │ ├── architecture.md # /architecture — show system design
│ │ ├── new-project.md # /new-project — scaffold new project
│ │ ├── security-check.md # /security-check — scan for secrets
│ │ ├── optimize-docker.md # /optimize-docker — Docker best practices
│ │ ├── create-e2e.md # /create-e2e — generate E2E tests
│ │ ├── create-api.md # /create-api — scaffold API endpoints
│ │ ├── worktree.md # /worktree — isolated task branches
│ │ ├── what-is-my-ai-doing.md # /what-is-my-ai-doing — live AI monitor
│ │ ├── setup.md # /setup — interactive .env configuration
│ │ ├── refactor.md # /refactor — audit + refactor against all rules
│ │ ├── install-global.md # /install-global — merge global config into ~/.claude/
│ │ └── diagram.md # /diagram — generate diagrams from actual code
│ ├── skills/
│ │ ├── code-review/SKILL.md # Triggered code review checklist
│ │ └── create-service/SKILL.md # Service scaffolding template
│ ├── agents/
│ │ ├── code-reviewer.md # Read-only review subagent
│ │ └── test-writer.md # Test writing subagent
│ └── hooks/
│ ├── block-secrets.py # PreToolUse: block sensitive files
│ ├── lint-on-save.sh # PostToolUse: lint after writes
│ ├── verify-no-secrets.sh # Stop: check for secrets
│ └── rulecatch-check.sh # Stop: report RuleCatch violations
├── project-docs/
│ ├── ARCHITECTURE.md # System overview (authoritative)
│ ├── INFRASTRUCTURE.md # Deployment details
│ └── DECISIONS.md # Architectural decision records
├── docs/ # GitHub Pages site
├── src/
│ ├── core/db/index.ts # Centralized database wrapper
│ ├── handlers/ # Business logic
│ ├── adapters/ # External service wrappers
│ └── types/ # Shared TypeScript types
├── scripts/
│ ├── db-query.ts # Test Query Master — dev/test query index
│ ├── queries/ # Individual dev/test query files
│ ├── build-content.ts # Markdown → HTML article builder
│ └── content.config.json # Article registry (SEO metadata)
├── content/ # Markdown source files for articles
├── tests/
│ ├── CHECKLIST.md # Master test tracker
│ ├── ISSUES_FOUND.md # User-guided testing log
│ ├── e2e/ # Playwright E2E tests
│ ├── unit/ # Vitest unit tests
│ └── integration/ # Integration tests
├── global-claude-md/ # Copy to ~/.claude/ (one-time setup)
│ ├── CLAUDE.md # Global security gatekeeper
│ └── settings.json # Global hooks config
├── .env.example
├── .gitignore
├── .dockerignore
├── package.json # All npm scripts (dev, test, db:query, etc.)
├── claude-mastery-project.conf # /new-project profiles + global root_dir
├── playwright.config.ts # E2E test config (test ports, webServer)
├── vitest.config.ts # Unit/integration test config
├── tsconfig.json
└── README.md
Three layers of protection working together:
- CLAUDE.md rules — Behavioral suggestions (weakest)
- Hooks — Guaranteed to run, stronger than rules, but not bulletproof
- Git safety — .gitignore as last line of defense (strongest)
Research shows 39% performance degradation when mixing topics, and a 2% misalignment early can cause 40% failure by end of conversation. Use /clear between unrelated tasks.
No file > 300 lines. No function > 50 lines. All tests pass. TypeScript compiles clean. These prevent the most common code quality issues in AI-assisted development.
With 10+ MCP servers, tool descriptions consume 50-70% of context. Tool Search lazy-loads on demand, saving 85% of context.
For non-trivial tasks, always start in plan mode. Don't let Claude write code until you've agreed on the plan. Bad plan = bad code.
Every step MUST have a unique name: Step 3 (Auth System). When you change a step, Claude must replace it — not append. Claude forgets this. If the plan contradicts itself, tell Claude: "Rewrite the full plan."
Every time Claude makes a mistake, add a rule to prevent it from happening again. Tell Claude: "Update CLAUDE.md so this doesn't happen again." Mistake rates actually drop over time. The file is checked into git — the whole team benefits from every lesson.
Auto-branch is on by default. Every command that modifies code automatically creates a feature branch when it detects you're on main. Zero friction — you never accidentally break main. Delete the branch if Claude screws up. Use /worktree for parallel sessions in separate directories. Set auto_branch = false in claude-mastery-project.conf to disable.
Every slash command and skill has two built-in enforcement steps: Auto-Branch (automatically creates a feature branch when on main — no manual step) and RuleCatch Report (checks for violations after completion). The rules aren't just documented — they're enforced at every touchpoint.
Types are specs that tell Claude what functions accept and return. Without types, Claude guesses — and guesses become runtime errors.
Most Windows developers don't know VS Code can run its entire backend inside WSL 2. HMR becomes 5-10x faster, Playwright tests run significantly faster, and file watching actually works. Your project must live on the WSL filesystem (~/projects/), NOT /mnt/c/. Run /setup to auto-detect.
The CLAUDE.md file is where you define the rules Claude Code must follow. These aren't suggestions — they're the operating manual for every session. Here are the critical rules included in this starter kit:
- NEVER commit passwords, API keys, tokens, or secrets to git/npm/docker
- NEVER commit
.envfiles — ALWAYS verify.envis in.gitignore - Before ANY commit: verify no secrets are included
- ALWAYS use TypeScript for new files (strict mode)
- NEVER use
anyunless absolutely necessary and documented why - When editing JavaScript files, convert to TypeScript first
- Types are specs — they tell you what functions accept and return
CORRECT: /api/v1/users
WRONG: /api/users
Every API endpoint MUST use /api/v1/ prefix. No exceptions.
- NEVER create direct database connections outside
src/core/db/ - ALWAYS use the centralized database wrapper
- All inputs auto-sanitized against NoSQL injection (disable with
DB_SANITIZE_INPUTS=false) - One connection pool. One place to change. One place to mock.
// CORRECT — explicit success criteria
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toContainText('Welcome');
// WRONG — passes even if broken
await page.goto('/dashboard');
// no assertion!ALWAYS use environment variables. NEVER put API keys, passwords, or tokens directly in code. NEVER hardcode connection strings — use DATABASE_URL from .env.
NEVER auto-deploy, even if the fix seems simple. NEVER assume approval — wait for explicit confirmation.
- No file > 300 lines (split if larger)
- No function > 50 lines (extract helper functions)
- All tests must pass before committing
- TypeScript must compile with no errors (
tsc --noEmit)
When multiple await calls are independent, ALWAYS use Promise.all. Before writing sequential awaits, evaluate: does the second call need the first call's result?
// CORRECT — independent operations run in parallel
const [users, products, orders] = await Promise.all([
getUsers(),
getProducts(),
getOrders(),
]);
// WRONG — sequential when they don't depend on each other
const users = await getUsers();
const products = await getProducts(); // waits unnecessarily
const orders = await getOrders(); // waits unnecessarily- Auto-branch is ON by default — commands auto-create feature branches when on main
- Branch names match the command:
refactor/<file>,test/<feature>,feat/<scope> - Use
/worktreefor parallel sessions in separate directories - Review the full diff (
git diff main...HEAD) before merging - If Claude screws up on a branch — delete it. Main was never touched.
- Disable with
auto_branch = falseinclaude-mastery-project.conf
Disabled by default. When enabled, NO docker push is allowed until the image passes local verification:
- Build the image
- Run the container locally
- Verify it doesn't crash (still running after 5s)
- Health endpoint returns 200
- No fatal errors in logs
- Clean up, then push
Enable with docker_test_before_push = true in claude-mastery-project.conf. Applies to all commands that push Docker images.
The CLAUDE.md also includes a "Check Before Assuming" pattern:
- Missing UI element? → Check feature gates BEFORE assuming bug
- Empty data? → Check if services are running BEFORE assuming broken
- 404 error? → Check service separation BEFORE adding endpoint
- Auth failing? → Check which auth system BEFORE debugging
- Test failing? → Read the error message fully BEFORE changing code
| Service | Dev Port | Test Port |
|---|---|---|
| Website | 3000 | 4000 |
| API | 3001 | 4010 |
| Dashboard | 3002 | 4020 |
CLAUDE.md rules are suggestions. Hooks are stronger — they're guaranteed to run as shell/python scripts at specific lifecycle points. But hooks are not bulletproof: Claude may still work around their output. They're a significant upgrade over CLAUDE.md rules alone, but not an absolute guarantee.
Runs before Claude reads or edits any file. Blocks access to sensitive files like .env, credentials.json, SSH keys, and .npmrc.
# Files that should NEVER be read or edited by Claude
SENSITIVE_FILENAMES = {
'.env', '.env.local', '.env.production',
'secrets.json', 'id_rsa', 'id_ed25519',
'.npmrc', 'credentials.json',
'service-account.json',
}
# Exit code 2 = block operation and tell Claude why
if path.name in SENSITIVE_FILENAMES:
print(f"BLOCKED: Access to '{file_path}' denied.", file=sys.stderr)
sys.exit(2)Runs after Claude writes or edits a file. Automatically checks TypeScript compilation, ESLint, or Python linting depending on file extension.
case "$EXTENSION" in
ts|tsx)
npx tsc --noEmit --pretty "$FILE_PATH" 2>&1 | head -20
;;
js|jsx)
npx eslint "$FILE_PATH" 2>&1 | head -20
;;
py)
ruff check "$FILE_PATH" 2>&1 | head -20
;;
esacRuns when Claude finishes a turn. Scans all staged git files for accidentally committed secrets using regex patterns for API keys, AWS credentials, and credential URLs.
# Check staged file contents for common secret patterns
if grep -qEi '(api[_-]?key|secret[_-]?key|password|token)\s*[:=]\s*["\x27][A-Za-z0-9+/=_-]{16,}' "$file"; then
VIOLATIONS="${VIOLATIONS}\n - POSSIBLE SECRET in $file"
fi
# Check for AWS keys
if grep -qE 'AKIA[0-9A-Z]{16}' "$file"; then
VIOLATIONS="${VIOLATIONS}\n - AWS ACCESS KEY in $file"
fiRuns when Claude finishes a turn. Checks RuleCatch for any rule violations detected during the session. Skips silently if RuleCatch isn't installed — zero overhead for users who haven't set it up yet.
Hooks are wired up in .claude/settings.json:
{
"hooks": {
"PreToolUse": [{
"matcher": "Read|Edit|Write",
"hooks": [{ "type": "command", "command": "python3 .claude/hooks/block-secrets.py" }]
}],
"PostToolUse": [{
"matcher": "Write",
"hooks": [{ "type": "command", "command": "bash .claude/hooks/lint-on-save.sh" }]
}],
"Stop": [{
"hooks": [
{ "type": "command", "command": "bash .claude/hooks/verify-no-secrets.sh" },
{ "type": "command", "command": "bash .claude/hooks/rulecatch-check.sh" }
]
}]
}
}Invoke these with /command in any Claude Code session. Each command is a markdown file in .claude/commands/ that gives Claude specific instructions and tool permissions.
Scans your actual code and generates ASCII diagrams automatically:
/diagram architecture— services, connections, data flow (scans src/, routes, adapters)/diagram api— all API endpoints grouped by resource with handler locations/diagram database— collections, indexes, relationships (scans queries + types)/diagram infrastructure— deployment topology, regions, containers (scans .env + Docker)/diagram all— generate everything at once
Writes to project-docs/ARCHITECTURE.md and project-docs/INFRASTRUCTURE.md. Uses ASCII box-drawing — works everywhere, no external tools needed. Add --update to write without asking.
One-time setup: installs the starter kit's global Claude config into ~/.claude/.
- Smart merge — if you already have a global
CLAUDE.md, it appends missing sections without overwriting yours - settings.json — merges deny rules and hooks (never removes existing ones)
- Hooks — copies
block-secrets.py,verify-no-secrets.sh, andrulecatch-check.shto~/.claude/hooks/
Reports exactly what was added, skipped, and merged. Your existing config is never overwritten.
Interactive project configuration. Walks you through setting up your .env with real values:
- Multi-region — US + EU with isolated databases, VPS, and Dokploy per region
- Database — MongoDB/PostgreSQL per region (
MONGODB_URI_US,MONGODB_URI_EU) - Deployment — Dokploy on Hostinger VPS per region (IP, API key, app ID, webhook token)
- Docker — Hub username, image name, region tagging (
:latestfor US,:eufor EU) - GitHub — username, SSH vs HTTPS
- Analytics — Rybbit site ID
- RuleCatch — API key, region
- Auth — auto-generates JWT secret
Multi-region writes the region map to both .env and CLAUDE.md so Claude always knows: US containers → US database, EU containers → EU database. Never cross-connects.
Skips variables that already have values. Use /setup --reset to re-configure everything. Never displays secrets back to you. Keeps .env.example in sync.
Launches the RuleCatch AI-Pooler live monitor in a separate terminal:
- Every tool call (Read, Write, Edit, Bash)
- Token usage and cost per turn
- Rule violations as they happen
- Which files are being accessed
# Run in a separate terminal
npx @rulecatch/ai-pooler@latest monitor -vZero token overhead — runs completely outside Claude's context. Also available as pnpm ai:monitor.
Systematic code review against a 7-point checklist:
- Security — OWASP Top 10, no secrets in code
- Types — No
any, proper null handling - Error Handling — No swallowed errors
- Performance — No N+1 queries, no memory leaks
- Testing — New code has explicit assertions
- Database — Using centralized wrapper
- API Versioning — All endpoints use
/api/v1/
Issues are reported with severity (Critical / Warning / Info), file:line references, and suggested fixes.
Smart commit with conventional commit format. Reviews staged changes, generates appropriate commit messages using the type(scope): description convention (feat, fix, docs, refactor, test, chore, perf). Warns if changes span multiple concerns and suggests splitting.
Generates a structured test plan for any feature with prerequisites, happy path scenarios with specific expected outcomes, error cases and edge cases, pass/fail criteria table, and sign-off tracker.
Scans the project for security vulnerabilities: secrets in code, .gitignore coverage, sensitive files tracked by git, .env handling audit, and dependency vulnerability scan (npm audit).
Checks the actual filesystem state and reports project status — source file counts by type, test coverage, recent git activity, and prioritized next actions.
Reads project-docs/ARCHITECTURE.md and displays the system overview, data flow diagrams, and service responsibility maps. If docs don't exist, scaffolds them.
Creates an isolated git worktree + branch for a task:
/worktree add-auth # → task/add-auth branch
/worktree feat/new-dashboard # → uses prefix as-isEach task gets its own branch and its own directory. Main stays untouched. Enables running multiple Claude sessions in parallel without conflicts. When done: merge into main (or open a PR), then git worktree remove.
Audits your Dockerfile against 12 production best practices: multi-stage builds, layer caching, Alpine base images, non-root user, .dockerignore coverage, frozen lockfile, health checks, no secrets in build args, and pinned versions. Generates an optimized Dockerfile with before/after image size comparison.
Generates a properly structured Playwright E2E test for a feature. Reads the source code, identifies URLs/elements/data to verify, creates the test at tests/e2e/[name].spec.ts with happy path, error cases, and edge cases. Verifies the test meets the "done" checklist before finishing.
Scaffolds a production-ready API endpoint with full CRUD:
- Types —
src/types/<resource>.ts(document, request, response shapes) - Handler —
src/handlers/<resource>.ts(business logic, indexes, CRUD) - Route —
src/routes/v1/<resource>.ts(thin routes, proper HTTP status codes) - Tests —
tests/unit/<resource>.test.ts(happy path, error cases, edge cases)
Uses the db wrapper with shared pool, auto-sanitized inputs, pagination (max 100), registered indexes, and /api/v1/ prefix. Pass --no-mongo to skip MongoDB integration.
Audit + refactor any file against every rule in CLAUDE.md:
- Branch check — verifies you're not on main (suggests
/worktree) - File size — >300 lines = must split
- Function size — >50 lines = must extract
- TypeScript — no
any, explicit types, strict mode - Import hygiene — no barrel imports, proper
import type - Error handling — no swallowed errors, proper logging
- Database access — wrapper only (
src/core/db/) - API routes —
/api/v1/prefix - Promise.all — parallelize independent awaits
- Security + dead code — no secrets, no unused code
Presents a named-step plan before making changes. Splits files by type (types → src/types/, validation → colocated, helpers → colocated). Updates all imports across the project.
/refactor src/handlers/users.ts
/refactor src/server.ts --dry-run # report only, no changesFull project scaffolding with profiles:
/new-project my-app clean
/new-project my-app default
/new-project my-app fullstack next dokploy seo tailwind pnpm
/new-project my-api api fastify dokploy docker multiregion
/new-project my-site static-siteclean — All Claude infrastructure (commands, skills, agents, hooks, project-docs, tests templates) with zero coding opinions. No TypeScript enforcement, no port assignments, no database wrapper, no quality gates. Your project, your rules — Claude just works.
default and other profiles — Full opinionated scaffolding with project type, framework, SSR, hosting (Dokploy/Vercel/static), package manager, database, extras (Tailwind, Prisma, Docker, CI), and MCP servers. Use claude-mastery-project.conf to save your preferred stack.
Skills are context-aware templates that activate automatically when Claude detects relevant triggers. Unlike commands (which you invoke), skills load themselves when needed.
Triggers: review, audit, check code, security review
A systematic review checklist covering security (OWASP, input validation, CORS, rate limiting), TypeScript quality (no any, explicit return types, strict mode), error handling (no swallowed errors, user-facing messages), performance (N+1 queries, memory leaks, pagination), and architecture compliance (database wrapper, API versioning, service separation). Each issue is reported with severity, location, fix, and why it matters.
Triggers: create service, new service, scaffold service
Generates a complete microservice following the server/handlers/adapters separation pattern:
┌─────────────────────────────────────────────────────┐
│ YOUR SERVICE │
├─────────────────────────────────────────────────────┤
│ SERVER (server.ts) │
│ → Express/Fastify entry point, defines routes │
│ → NEVER contains business logic │
│ │ │
│ ▼ │
│ HANDLERS (handlers/) │
│ → Business logic lives here │
│ → One file per domain │
│ │ │
│ ▼ │
│ ADAPTERS (adapters/) │
│ → External service wrappers │
│ → Database, APIs, etc. │
└─────────────────────────────────────────────────────┘
Includes package.json, tsconfig.json, entry point with error handlers, health check endpoint, and a post-creation verification checklist.
Agents are specialists that Claude delegates to automatically. They run with restricted tool access so they can't accidentally modify your code when they shouldn't.
Tools: Read, Grep, Glob (read-only)
"You are a senior code reviewer. Your job is to find real problems — not nitpick style."
Priority order:
- Security — secrets in code, injection vulnerabilities, auth bypasses
- Correctness — logic errors, race conditions, null pointer risks
- Performance — N+1 queries, memory leaks, missing indexes
- Type Safety —
anyusage, missing null checks, unsafe casts - Maintainability — dead code, unclear naming (lowest priority)
If the code is good, it says so — it doesn't invent issues to justify its existence.
Tools: Read, Write, Grep, Glob, Bash
"You are a testing specialist. You write tests that CATCH BUGS, not tests that just pass."
Principles:
- Every test MUST have explicit assertions — "page loads" is NOT a test
- Test behavior, not implementation details
- Cover happy path, error cases, AND edge cases
- Use realistic test data, not
"test"/"asdf" - Tests should be independent — no shared mutable state
// GOOD — explicit, specific assertions
expect(result.status).toBe(200);
expect(result.body.user.email).toBe('test@example.com');
// BAD — passes even when broken
expect(result).toBeTruthy(); // too vagueThe starter kit includes a production-grade MongoDB wrapper at src/core/db/index.ts using the native driver (no Mongoose, no ODMs). It enforces every best practice that prevents the most common database failures in AI-assisted development.
ALL database access goes through src/core/db/index.ts. No exceptions. Never create new MongoClient() anywhere else. Never import mongodb directly in business logic.
// CORRECT — import from the centralized wrapper
import { queryOne, insertOne, updateOne } from '@/core/db/index.js';
// WRONG — NEVER do this
import { MongoClient } from 'mongodb'; // FORBIDDEN outside src/core/db/// Single document (automatic $limit: 1)
const user = await queryOne<User>('users', { email });
// Pipeline query
const recent = await queryMany<Order>('orders', [
{ $match: { userId, status: 'active' } },
{ $sort: { createdAt: -1 } },
{ $limit: 20 },
]);
// Join — $limit enforced BEFORE $lookup automatically
const userWithOrders = await queryWithLookup<UserWithOrders>('users', {
match: { _id: userId },
lookup: { from: 'orders', localField: '_id', foreignField: 'userId', as: 'orders' },
});// Insert
await insertOne('users', { email, name, createdAt: new Date() });
await insertMany('events', batchOfEvents);
// Update — use $inc for counters (NEVER read-modify-write)
await updateOne<Stats>('stats',
{ date },
{ $inc: { pageViews: 1 } },
true // upsert
);
// Complex batch (auto-retries E11000 concurrent races)
await bulkOps('sessions', [
{ updateOne: { filter: { sessionId }, update: { $inc: { events: 1 } }, upsert: true } },
]);| Preset | Max Pool | Min Pool | Use Case |
|---|---|---|---|
high |
20 | 2 | APIs, high-traffic services |
standard |
10 | 2 | Default for most services |
low |
5 | 1 | Background workers, cron jobs |
- Singleton per URI — same URI always returns the same client, prevents pool exhaustion
- Next.js hot-reload safe — persists connections via
globalThisduring development - NoSQL injection sanitization — automatic on all inputs (configurable)
- Transaction support —
withTransaction()for multi-document atomic operations - Change Stream access —
rawCollection()for real-time event processing - Graceful shutdown —
gracefulShutdown()closes all pools onSIGTERM,SIGINT,uncaughtException, andunhandledRejection— no zombie connections on crash - E11000 auto-retry — handles concurrent upsert race conditions automatically
- $limit before $lookup —
queryWithLookup()enforces this for join performance - Index management —
registerIndex()+ensureIndexes()at startup
Every dev/test database query gets its own file in scripts/queries/ and is registered in the master index. Production code in src/ stays clean.
// scripts/queries/find-expired-sessions.ts
import { queryMany } from '../../src/core/db/index.js';
export default {
name: 'find-expired-sessions',
description: 'Find sessions that expired in the last 24 hours',
async run(args: string[]): Promise<void> {
const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000);
const sessions = await queryMany('sessions', [
{ $match: { expiresAt: { $lt: cutoff } } },
{ $sort: { expiresAt: -1 } },
{ $limit: 50 },
]);
console.log(`Found ${sessions.length} expired sessions`);
},
};Register in scripts/db-query.ts and run: npx tsx scripts/db-query.ts find-expired-sessions
A config-driven Markdown-to-HTML article builder. Write content in content/ as Markdown, register it in scripts/content.config.json, and build fully SEO-ready static HTML pages. Each generated page includes Open Graph, Twitter Cards, Schema.org JSON-LD, syntax highlighting, and optional sidebar TOC.
pnpm content:build # Build all published articles
pnpm content:build:id my-post # Build a single article
pnpm content:list # List all articles and statusPre-structured docs that Claude actually follows. Each template uses the "STOP" pattern — explicit boundaries that prevent Claude from making unauthorized changes.
project-docs/ARCHITECTURE.md — Starts with "This document is AUTHORITATIVE. No exceptions." Includes ASCII architecture diagram with data flow, service responsibility table (Does / Does NOT), technology choices with rationale, and an "If You Are About To... STOP" section that blocks scope creep.
## If You Are About To...
- Add an endpoint to the wrong service → STOP. Check the table above.
- Create a direct database connection → STOP. Use the wrapper.
- Skip TypeScript for a quick fix → STOP. TypeScript is non-negotiable.
- Deploy without tests → STOP. Write tests first.
project-docs/DECISIONS.md — Architectural Decision Records (ADRs) that document why you chose X over Y. Includes two starter decisions:
- ADR-001: TypeScript Over JavaScript — AI needs explicit type contracts to avoid guessing
- ADR-002: Centralized Database Wrapper — prevents connection pool exhaustion
Each ADR has: Context, Decision, Alternatives Considered (with pros/cons table), and Consequences.
project-docs/INFRASTRUCTURE.md — Deployment and environment details: environment overview diagram, environment variables table, deployment prerequisites and steps, rollback procedures, and monitoring setup.
From the V5 testing methodology — a structured approach to testing that prevents the most common AI-assisted testing failures.
tests/CHECKLIST.md — A master test status tracker that gives you a single-glance view of what's tested and what's not. Uses visual status indicators for every feature area.
tests/ISSUES_FOUND.md — A user-guided testing log where you document issues discovered during testing. Each entry includes: what was tested, what was expected, what actually happened, severity, and current status. Queue observations, fix in batch — not one at a time.
Every E2E test (Playwright) must verify:
- Correct URL after navigation
- Key visible elements are present
- Correct data is displayed
- Error states show proper messages
The Playwright config is pre-wired with test ports, automatic server spawning, and port cleanup:
pnpm test:e2e— kills anything on test ports (4000, 4010, 4020)- Playwright spawns servers via
webServerconfig on test ports - Tests run against the test servers
- Servers shut down automatically when tests complete
pnpm test # ALL tests (unit + E2E)
pnpm test:unit # Unit/integration only (Vitest)
pnpm test:e2e # E2E only (kills ports → spawns servers → Playwright)
pnpm test:e2e:headed # E2E with visible browser
pnpm test:e2e:ui # E2E with Playwright UI mode
pnpm test:e2e:report # Open last HTML reportIf you're developing on Windows, this is the single biggest performance improvement you can make.
VS Code can run its entire backend inside WSL 2 while the UI stays on Windows. Your terminal, extensions, git, Node.js, and Claude Code all run natively in Linux.
| Without WSL Mode | With WSL Mode |
|---|---|
| HMR takes 2-5 seconds per change | HMR is near-instant (<200ms) |
| Playwright tests are slow and flaky | Native Linux speed |
| File watching misses changes | Reliable and fast |
| Node.js ops hit NTFS translation | Native ext4 filesystem |
git status takes seconds |
Instant |
# 1. Install WSL 2 (PowerShell as admin)
wsl --install
# 2. Restart your computer
# 3. Install VS Code extension
# Search for "WSL" by Microsoft (ms-vscode-remote.remote-wsl)
# 4. Connect VS Code to WSL
# Click green "><" icon in bottom-left → "Connect to WSL"
# 5. Clone projects INSIDE WSL (not /mnt/c/)
mkdir -p ~/projects
cd ~/projects
git clone git@github.com:YourUser/your-project.git
code your-project # opens in WSL mode automaticallyYour project MUST live on the WSL filesystem (~/projects/), NOT on /mnt/c/. Having WSL but keeping your project on the Windows filesystem gives you the worst of both worlds.
# Check your setup:
pwd
# GOOD — native Linux filesystem
/home/you/projects/my-app
# BAD — still hitting Windows filesystem through WSL
/mnt/c/Users/you/projects/my-appRun /setup in Claude Code to auto-detect your environment and get specific instructions.
The global CLAUDE.md lives at ~/.claude/CLAUDE.md and applies to every project you work on. It's your organization-wide security gatekeeper.
The starter kit includes a complete global config template in global-claude-md/ with:
- Absolute Rules — NEVER publish sensitive data. NEVER commit
.envfiles. NEVER auto-deploy. NEVER hardcode credentials. NEVER rename without a plan. These apply to every project, every session. - New Project Standards — Every new project automatically gets:
.env+.env.example, proper.gitignore,.dockerignore, TypeScript strict mode,src/tests/project-docs/.claude/directory structure. - Coding Standards — Error handling requirements, testing standards, quality gates, database wrapper pattern — all enforced across every project.
- Global Permission Denials — The companion
settings.jsonexplicitly denies Claude access to.env,.env.local,secrets.json,id_rsa, andcredentials.jsonat the permission level — before hooks even run.
// CORRECT — explicit, typed
import { getUserById } from './handlers/users.js';
import type { User } from './types/index.js';
// WRONG — barrel imports that pull everything
import * as everything from './index.js';// CORRECT — handle errors explicitly
try {
const user = await getUserById(id);
if (!user) throw new NotFoundError('User not found');
return user;
} catch (err) {
logger.error('Failed to get user', { id, error: err });
throw err;
}
// WRONG — swallow errors silently
try {
return await getUserById(id);
} catch {
return null; // silent failure
}Renaming packages, modules, or key variables mid-project causes cascading failures. If you must rename:
- Create a checklist of ALL files and references first
- Use IDE semantic rename (not search-and-replace)
- Full project search for old name after renaming
- Check:
.md,.txt,.env, comments, strings, paths - Start a FRESH Claude session after renaming
Every plan step MUST have a unique, descriptive name:
Step 1 (Project Setup): Initialize repo with TypeScript
Step 2 (Database Layer): Create MongoDB wrapper
Step 3 (Auth System): Implement JWT authentication
When modifying a plan:
- REPLACE the named step entirely: "Change Step 3 (Auth System) to use session cookies"
- NEVER just append: "Also, use session cookies" ← Step 3 still says JWT
- After any change, Claude must rewrite the full updated plan
- If the plan contradicts itself, tell Claude: "Rewrite the full plan — Step 3 and Step 7 contradict"
- If fundamentally changing direction:
/clear→ state requirements fresh
| Command | What it does |
|---|---|
| Development | |
pnpm dev |
Dev server with hot reload |
pnpm dev:website |
Dev server on port 3000 |
pnpm dev:api |
Dev server on port 3001 |
pnpm dev:dashboard |
Dev server on port 3002 |
pnpm build |
Type-check + compile TypeScript |
pnpm start |
Run production build |
pnpm typecheck |
TypeScript check only (no emit) |
| Testing | |
pnpm test |
Run ALL tests (unit + E2E) |
pnpm test:unit |
Unit/integration tests (Vitest) |
pnpm test:unit:watch |
Unit tests in watch mode |
pnpm test:coverage |
Unit tests with coverage report |
pnpm test:e2e |
E2E tests (kills ports → spawns servers → Playwright) |
pnpm test:e2e:headed |
E2E with visible browser |
pnpm test:e2e:ui |
E2E with Playwright UI mode |
pnpm test:e2e:chromium |
E2E on Chromium only (fast) |
pnpm test:e2e:report |
Open last Playwright HTML report |
pnpm test:kill-ports |
Kill processes on test ports (4000, 4010, 4020) |
| Database | |
pnpm db:query <name> |
Run a dev/test database query |
pnpm db:query:list |
List all registered queries |
| Content | |
pnpm content:build |
Build all published MD → HTML |
pnpm content:build:id <id> |
Build a single article by ID |
pnpm content:list |
List all articles |
| Monitoring & Docker | |
pnpm ai:monitor |
Live AI activity monitor (run in separate terminal) |
pnpm docker:optimize |
Audit Dockerfile (use /optimize-docker in Claude) |
| Utility | |
pnpm clean |
Remove dist/, coverage/, test-results/ |
This starter kit gives you rules, hooks, and quality gates. RuleCatch.AI tells you when they're broken.
RuleCatch monitors AI-assisted development sessions in real-time using the same Claude Code hooks system this kit teaches — zero token overhead, completely invisible to the AI model.
What it does:
- 200+ pre-built rules across security, TypeScript, React, Next.js, MongoDB, Docker, and more — violations detected in under 100ms
- Session analytics — token usage, cost per session, lines per hour, correction rates
- MCP integration — ask Claude directly:
"RuleCatch, what was violated today?" - Dashboard & reporting — full violation analytics, trend reports, team insights, alerts via Slack, Discord, PagerDuty, and more
- Privacy-first — AES-256-GCM client-side encryption; you hold the key
Quick setup:
# Install the AI-Pooler (hooks into Claude Code automatically)
npx @rulecatch/ai-pooler init --api-key=dc_your_key --region=us
# Add the MCP server to query violations from Claude
npx @rulecatch/mcp-server initnpm: @rulecatch/ai-pooler · @rulecatch/mcp-server
Explore RuleCatch.AI → · 7-day free trial
# Live documentation (eliminates outdated API answers)
claude mcp add context7 -- npx -y @upstash/context7-mcp@latest
# GitHub integration (PRs, issues, CI/CD)
claude mcp add github -- npx -y @modelcontextprotocol/server-github
# E2E testing
claude mcp add playwright -- npx -y @anthropic-ai/playwright-mcp
# AI development analytics & rule monitoring (RuleCatch.AI)
npx @rulecatch/mcp-server initSee the V4 guide for the complete MCP server directory.
Based on the Claude Code Mastery Guide series by TheDecipherist:
- V1: Global CLAUDE.md, Security Gatekeeper, Project Scaffolding, Context7
- V2: Skills & Hooks, Enforcement over Suggestion, Quality Gates
- V3: LSP, CLAUDE.md, MCP, Skills & Hooks
- V4: 85% Context Reduction, Custom Agents & Session Teleportation
- V5: Renaming Problem, Plan Mode, Testing Methodology & Rules That Stick
Community contributors: u/BlueVajra, u/stratofax, u/antoniocs, u/GeckoLogic, u/headset38, u/tulensrma, u/jcheroske, u/ptinsley, u/Keksy, u/lev606

