Based on Claude Code Mastery V1–V5

The Definitive Starting Point
for Claude Code Projects

A ready-to-use project template with every best practice baked in, including the MDD (Manual-First Development) workflow. Stop reading 4,000+ lines of guides β€” clone this and start building.

Claude Code Starter Kit - The Definitive Starting Point for Claude Code Projects

What's Included

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 numbered critical rules for security, TypeScript, StrictDB, testing, and deployment.

Global CLAUDE.md

Security gatekeeper for all projects. Never publish secrets, never commit .env files, standardized scaffolding rules.

10 Hooks

Deterministic enforcement that always runs. Block secrets, lint on save, verify no credentials, branch protection, port conflicts, Rybbit pre-deploy gate, E2E test gate, env sync warnings, RuleCatch monitoring (optional β€” skips silently if not installed), and SessionStart context injection (session-context.sh) β€” injects .mdd/.startup.md at session start so Claude is oriented in ~100 tokens.

28 Slash Commands (17 project + 11 kit management)

/mdd, /help, /quickstart, /install-global, /install-mdd, /setup, /show-user-guide, /diagram, /review, /commit, /progress, /test-plan, /architecture, /new-project, /security-check, /optimize-docker, /create-e2e, /create-api, /worktree, /what-is-my-ai-doing, /refactor, /set-project-profile-default, /add-project-setup, /projects-created, /remove-project, /convert-project-to-starter-kit, /update-project, /add-feature

Skills

Context-aware templates that load on demand. 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, not just β€œpage loads.”

Documentation

Pre-structured ARCHITECTURE.md, INFRASTRUCTURE.md, and DECISIONS.md templates that Claude actually follows.

Testing Templates

Master test checklist, issue tracking log, and StrictDB β€” a unified database driver that prevents connection pool explosion. Built-in sanitization and guardrails allow safe operators while stripping dangerous ones.

Live AI Monitor

See every tool call, token, cost, and file access in real-time. Free monitor mode works instantly β€” no API key, no setup. Run pnpm ai:monitor in a separate terminal. Zero token overhead.

MDD Workflow STANDALONE

Manual-First Development β€” the built-in methodology that turns Claude Code from a code generator into a development partner. Every feature starts with documentation. Every fix starts with an audit.

MDD is now a standalone npm package β€” separated from this starter kit so you can install and use it in any project independently. Install it once globally; it works everywhere.
TheDecipherist/mdd @thedecipherist/mdd
We used MDD to audit this starter kit. Result: 20 findings discovered, 17 fixed, and 125 tests written from zero β€” all in 23 minutes. The methodology the starter kit teaches was used to audit the starter kit itself.
Parallel workflows supported. /mdd now asks if you want to work in an isolated worktree β€” run multiple /mdd sessions simultaneously, each in its own directory and branch. Use /worktree for complete isolation.

Stop Reducing Tokens. Start Clarifying Context.

I’ve tried every approach to improve Claude’s output. Context managers, prompt compression, elaborate system prompts. Then I built MDD, and I haven’t needed any of them since. I use MDD in every Claude project I work on now. The difference in results is night and day.

Here’s what changed my thinking: token reduction tools solve the wrong problem. Compressing context means Claude fills the gaps with assumptions. Assumptions become bugs. The more you compress, the more follow-up sessions it takes to fix what Claude misunderstood.

MDD does the opposite. One feature doc instead of 40 source files. The .mdd/.startup.md snapshot orients Claude in ~100–200 tokens at the start of every session β€” not because we removed information, but because we made it dense. Every token earns its place. Claude reads less, understands more, and produces better output on the first pass.

Token reduction is a side effect of clarity. It is not the goal. The goal is results that don’t require three sessions to fix.

What is MDD?

Most people prompt Claude Code like this: "fix the bug in my auth system." Claude reads 40 files, burns through context trying to understand your architecture, and produces something that technically compiles but misses the bigger picture.

MDD flips this. You write structured documentation first, then Claude reads one doc instead of 40 files. It gets the full picture in 200 tokens instead of 20,000. Every phase reads the output of the previous phase, compressing context further at each step.

The Workflow

πŸ“‹
Document Write feature docs with YAML frontmatter
πŸ”
Audit Read code, write incremental notes to disk
πŸ“Š
Analyze Produce severity-rated findings report
πŸ”§
Fix Execute pre-planned fixes with tests
βœ…
Verify Tests pass, types check, docs updated

Usage

One command, fifteen modes:

# Build a new feature (Analyze β†’ Document β†’ Test skeletons β†’ Plan β†’ Implement β†’ Verify)
/mdd user authentication with JWT tokens

# Audit existing code (Scope β†’ Read + Notes β†’ Analyze β†’ Present β†’ Fix)
/mdd audit
/mdd audit database    # audit a specific section

# Check MDD status β€” includes lightweight drift summary
/mdd status

# Detect doc drift: source files changed outside MDD since last sync
/mdd scan

# Update an existing feature doc after code changed
/mdd update 04

# Generate docs from code, or regenerate + compare an existing doc
/mdd reverse-engineer src/handlers/payments.ts
/mdd reverse-engineer 07

# Show ASCII dependency graph with broken/risky dep warnings
/mdd graph

# Archive a deprecated feature cleanly
/mdd deprecate 03

# Fix all UNTRACKED docs in one pass (missing last_synced/status/phase)
/mdd upgrade

# ── Initiative / Wave Planning (NEW) ──────────────────────────────────────────

# Create an initiative (groups related waves into one roadmap item)
/mdd plan-initiative "auth system"             # guided mode
/mdd plan-initiative "auth system" --template  # write raw markdown yourself

# Add a wave (a phase of work with a concrete demo state)
/mdd plan-wave auth-system "Auth Foundation"

# Execute a wave β€” turns planned features into MDD docs
/mdd plan-execute auth-system-wave-1

# Re-stamp waves after editing the parent initiative
/mdd plan-sync auth-system

# Remove a feature from a wave (before it has a doc)
/mdd plan-remove-feature auth-system-wave-1 auth-signup

# Cancel an initiative and all planned work
/mdd plan-cancel-initiative auth-system

# Show a reference table of every /mdd mode and what it does
/mdd commands

Build Mode β€” New Features

When you run /mdd <feature description>, Claude follows a structured 7-phase process:

  1. Phase 1 β€” Understand β€” Reads your architecture, existing docs, asks all questions upfront
  2. Phase 2 β€” Analyze β€” Data Flow & Impact Analysis (mandatory gate): reads the existing code the feature will touch, traces every data value end-to-end (backend β†’ API β†’ frontend β†’ UI transformation), checks for parallel computations of the same concept, greps for all usages of modified endpoints, and presents findings before documentation begins. Skipped automatically on greenfield projects (<5 source files, no existing MDD docs).
  3. Phase 3 β€” Document β€” Creates a numbered MDD doc in .mdd/docs/ with full YAML frontmatter including a data_flow: field pointing to the Phase 2 analysis
  4. Phase 4 β€” Test Skeletons + Red Gate β€” Generates failing tests from the documentation (Doc β†’ Test β†’ Code). Unit and E2E skeletons generated in parallel when both are needed. Red Gate then runs the new test files to confirm every skeleton actually fails β€” any skeleton that passes vacuously (no real assertion) or is already satisfied by pre-existing code is fixed before implementation begins.
  5. Phase 5 β€” Plan β€” Presents the build plan as commit-worthy blocks: each block has a runnable end-state, a conventional commit scope, a verification command, and a handoff contract. Independent blocks are annotated for parallel execution after a file-overlap and type-dependency gate. Simple features (<3 files, no API, no DB) keep the flat step format.
  6. Phase 6 β€” Implement + Green Gate β€” Executes blocks in dependency-layer order. Parallel blocks launch 2 agents simultaneously with self-contained prompts; a typecheck runs after each parallel batch before the next layer starts. Each block runs a Green Gate: a 5-iteration diagnosis-first loop. Every iteration requires stating the exact root cause and one targeted fix before applying it. At iteration 5, the loop stops and reports to the user β€” no blind retrying. Regression check runs after each block goes green.
  7. Phase 7 β€” Verify + Integration Gate β€” Phase 7a: full test suite + typecheck. Phase 7b: Integration Gate verifies real behavior (real HTTP calls, real DB writes, real browser rendering β€” feature-type-aware checklist). Default stance on any anomaly: β€œmy code is wrong until proven otherwise” β€” read logs, run a minimal probe, form a specific hypothesis before accepting an external blocker. Phase 7c: reports βœ… MDD Complete if verified, or ⏸ MDD Blocked with a concrete next step if an external condition prevented verification.

Tests are generated before code. They define the finish line. If a test fails, the implementation gets fixed β€” not the test. The Red Gate ensures the finish line is actually a finish line.

Why Phase 2 matters: In a maturing project, the most common class of bug isn’t in the new code β€” it’s in the assumption that existing data is correct and consistent. An AI sees projectedProgress: number on a type and assumes it’s ready to use, without tracing how that value was computed. Phase 2 forces that trace to happen before a single line of documentation is written, catching divergent parallel computations before they become UI bugs that take 3 sessions to debug.

Audit Mode β€” Existing Code

When you run /mdd audit, Claude runs a complete security and quality audit:

  1. Scope β€” Reads all .mdd/docs/ files, builds the feature map
  2. Read + Notes β€” Parallelized: features batched across up to 3 parallel Explore agents, each reading assigned source files and returning structured notes; main conversation is single writer. Single-feature audits stay sequential. Notes written to disk so findings survive context compaction.
  3. Analyze β€” Reads only the notes (not source code again), produces findings report
  4. Present β€” Shows top issues with severity, estimated fix time, asks what to fix
  5. Fix β€” Applies fixes from the report, writes tests, updates documentation

More Modes β€” Drift Detection, Doc Lifecycle & Planning

  • /mdd task <description> β€” Task mode. Identical to Build mode, but stamps the resulting doc with type: task β€” frozen after completion and permanently excluded from drift detection. Use for one-off work (investigations, refactors, tooling sessions) that is done-and-finished by definition. Task docs appear in a separate frozen section in /mdd scan and are counted separately in /mdd status.
  • /mdd scan β€” Detects documentation drift. Parallelized: a single Explore agent runs all git log --after="<last_synced>" checks in one pass and returns a classification table, eliminating the sequential bottleneck on large feature sets. Reports βœ… in sync / ⚠️ drifted / ❌ broken / ❓ untracked. Task docs (type: task) are excluded from drift checks and shown in a separate frozen section. Also checks for stale waves (wave initiativeVersion out of sync with parent initiative). The fix for drift is /mdd update.
  • /mdd update <feature-id> β€” Re-syncs an existing feature doc after code has changed. Diffs code vs doc, presents what changed, rewrites only the affected sections, appends new test skeletons for new behaviors, and updates last_synced in frontmatter.
  • /mdd reverse-engineer [path|id] β€” Generates MDD docs from existing code. Works on undocumented files (new doc) or existing docs (regenerate + compare). Parallelized for multi-file scope: ≀3 files read in main conversation; 4+ files batched across up to 3 Explore agents returning structured inference output (purpose, models, routes, rules, edge cases), synthesized into the doc draft. In regenerate mode, shows old vs new side-by-side so you can merge rather than overwrite.
  • /mdd graph β€” Renders an ASCII dependency map from depends_on fields. Flags broken dependencies (deprecated features still referenced), risky dependencies (complete features depending on draft/in-progress ones), and orphans. When .mdd/initiatives/ exists, also renders an initiative β†’ wave β†’ feature hierarchy tree with progress indicators and broken doc-path warnings.
  • /mdd deprecate <feature-id> β€” Retires a feature: sets status: deprecated, moves doc to .mdd/docs/archive/, adds known-issue warnings to all dependents, and optionally deletes source and test files (asks separately for each).
  • /mdd upgrade β€” Batch-patches missing last_synced, status, and phase frontmatter fields across all .mdd/docs/ files. Non-destructive β€” existing fields are never overwritten. last_synced is inferred from git log on each doc file (preserving actual history, not defaulting to today). Shows a full plan before writing. Run this once if the MDD Dashboard shows all docs as UNTRACKED (❓) β€” it converts them all to IN SYNC in a single pass.
  • /mdd commands β€” Prints a reference table of every MDD mode and what it does. Output is derived from the mode-detection block in mdd.md at runtime, so it stays in sync automatically as new modes are added β€” nothing is hardcoded.
  • MDD versioning β€” Every file created or updated by MDD is stamped with mdd_version: N in its frontmatter, matching the version declared in mdd.md. /mdd status shows a breakdown of files by version so you can see at a glance what’s out of sync. /install-mdd and /install-global mdd compare mdd_version between source and installed file before overwriting β€” no silent updates. Files without mdd_version (created before versioning) are treated as version 0 and flagged as outdated.

Initiative & Wave Planning NEW

MDD Waves adds a three-level planning hierarchy on top of feature docs: Initiatives β†’ Waves β†’ Feature docs. An initiative is a roadmap item (e.g., β€œAuth System”); a wave is a phase of that initiative with a concrete demo state; feature docs are the individual MDD docs built by /mdd plan-execute.

  • /mdd plan-initiative <title> β€” Creates a new initiative in .mdd/initiatives/. Guided mode interviews you about goals, target audience, and open product questions. --template flag skips the interview and writes the raw markdown file for you to fill in. Collision-checks slugs against existing initiatives and blocks if active wave docs exist for that slug.
  • /mdd plan-wave <initiative-id> <wave-title> β€” Adds a wave to an existing initiative. Captures the demo state (what a user can do when this wave ships), the feature list with inter-feature dependencies, and open research questions. Writes to .mdd/waves/ stamped with the initiative’s current version.
  • /mdd plan-execute <wave-id> β€” Runs /mdd <feature> build mode for each planned feature in the wave that doesn’t have a doc yet. Supports automated (run all) or interactive (confirm each) modes. Updates docPath and waveStatus in the wave file as docs are created.
  • /mdd plan-sync <initiative-id> β€” Re-stamps all child wave files with the initiative’s current version after the initiative is edited. Run this to clear stale-wave warnings from /mdd scan.
  • /mdd plan-remove-feature <wave-id> <feature-slug> β€” Removes a feature from a wave before it has been executed. Hard-stops if the feature already has a docPath β€” use /mdd deprecate for that.
  • /mdd plan-cancel-initiative <initiative-id> β€” Sets the initiative and all child waves to cancelled. Warns if any wave has executed features and asks how to handle them. Cancelled initiatives remain visible in the TUI dashboard (shown in gray) for historical reference.

The MDD Dashboard TUI gains a collapsible INITIATIVES section at the top of the left panel. Press Enter or β†’ on an initiative to expand its waves; press i to jump directly to the first initiative. The status bar shows total initiative count and active wave progress.

The .mdd/ Directory

All MDD artifacts live in a single dotfile directory, gitignored by default:

.mdd/
β”œβ”€β”€ docs/                        # Feature documentation (one per feature)
β”‚   β”œβ”€β”€ 01-project-scaffolding.md  # YAML frontmatter: last_synced, status, phase
β”‚   β”œβ”€β”€ 02-profile-system.md
β”‚   └── archive/                 # Deprecated feature docs (/mdd deprecate)
β”œβ”€β”€ initiatives/                 # Initiative files (/mdd plan-initiative)
β”‚   └── auth-system.md           # id, title, status, version, hash, overview
β”œβ”€β”€ waves/                       # Wave files (/mdd plan-wave)
β”‚   └── auth-system-wave-1.md    # features table + docPath, waveStatus per feature
└── audits/                      # Audit artifacts
    β”œβ”€β”€ notes-2026-03-01.md      # Raw reading notes
    β”œβ”€β”€ report-2026-03-01.md     # Structured findings
    β”œβ”€β”€ results-2026-03-01.md    # Before/after summary
    β”œβ”€β”€ scan-2026-04-12.md       # Drift report (/mdd scan)
    └── graph-2026-04-12.md      # Dependency graph (/mdd graph)

Real Results: Self-Audit

We used MDD to audit this starter kit β€” the same methodology the kit teaches. Here's what happened:

PhaseTimeOutput
Phase 0: Documentation~25 min9 feature docs (795 lines) in .mdd/docs/
Phase 1: Read + Notes9 min 51s57+ files read, 837 lines of notes
Phase 2: Analyze2 min 39s298-line report, 20 findings
Phase 3: Fix All10 min 53s17/20 fixed, 125 tests written
Total~48 min20 findings, 125 tests from zero
MetricBefore MDDAfter MDD
Unit tests094
Test files05
Documentation files314
Known issues documented084
Findings found & fixed017/20
Quality gate violations1 (651-line file)0 (split into 5 modules)
Config validationNone (raw JSON.parse)Zod schema with fail-fast
Secret detection patterns4 basic10+ (GitHub, Slack, Stripe, PEM, JWT)

Why It Works

The problem with Claude Code isn't intelligence β€” it's context. A 200K token window sounds huge until you're reading 40 files and burning 80% of context on comprehension before writing a single line of output.

MDD makes each phase a context compressor: documentation compresses 40 files into 1 doc, raw notes compress all source code into a single file, the audit report compresses notes into severity-rated findings. By the time Claude writes code, it's working from a 300-line report β€” not a 40,000-line codebase. It's not problem-solving. It's pattern-matching.

The Incremental Write Trick

The most important technical detail: when Claude reads files during an audit, context will compact. If your findings are only in Claude's memory, they're gone.

Instead, Claude writes notes to disk every 2 features. If context compacts, it reads the tail of the notes file and picks up where it left off. We've run this pattern across 6 complete audit cycles. Zero data loss.

After processing every 2 features, immediately append your notes to
.mdd/audits/notes.md. If context compacts, read the TAIL of the notes
file and continue from where you left off.

Startup Context

Every Claude Code session starts cold. Without context, Claude reads dozens of files to understand your project β€” burning thousands of tokens before writing a single line of output. The MDD Startup Context system eliminates this entirely.

.mdd/.startup.md is a compact project snapshot that the SessionStart hook injects automatically at the start of every session β€” including after /clear and after context compaction. Claude reads one file (~100–200 tokens) instead of your entire codebase. It is regenerated automatically by /mdd commands and gitignored β€” it is machine state, not source code.

The two-zone model:
  • Auto-generated zone (above the --- divider) β€” rebuilt automatically at several points: after /mdd <feature> writes documentation (Phase 3), after /mdd audit produces a findings report (Phase A3), after audit fixes complete (Phase A5), and on-demand via /mdd status. Contains git branch, stack summary, features list, last audit results, and rules quick-reference.
  • Notes zone (below the --- divider) β€” append-only, never overwritten. Your own timestamped annotations added with /mdd note.

Example file:

## Project Snapshot
Generated: 2026-03-04 | Branch: feat/webserver

## Stack
Framework: Next.js | DB: MongoDB (StrictDB) | Host: Dokploy

## Features Documented (4)
01-project-scaffolding -- complete
02-profile-system -- complete
03-auth -- complete
04-webserver -- IN PROGRESS

## Last Audit
Date: 2026-03-01 | Findings: 20 | Fixed: 17 | Open: 3
Open: ssl-redeploy-race, nginx-log-tab, e2e-coverage-gap

## Rules Summary
Read CLAUDE.md for full rules. Key rules:
- TypeScript always, strict mode, no any
- StrictDB only -- no raw drivers
- /api/v1/ prefix on all endpoints
- No file > 300 lines, no function > 50 lines
- Never commit .env

---

## Notes
- [2026-03-04] ssl issue is a docker swarm bug, not nginx
- [2026-03-04] waiting on Anthropic SessionStart fix for startup source
CommandWhat it does
/mdd statusRegenerate .startup.md from current project state
/mdd note "text"Append a timestamped note to the Notes zone
/mdd note listPrint only the Notes section
/mdd note clearWipe the Notes section (asks for confirmation)

The hook that powers this is session-context.sh β€” wired to fire on startup, clear, and compact sources. The resume source is intentionally excluded: when resuming a session, Claude already has the transcript and injecting context again wastes tokens.

"SessionStart": [
  {
    "matcher": "startup|clear|compact",
    "hooks": [
      {
        "type": "command",
        "command": "bash .claude/hooks/session-context.sh"
      }
    ]
  }
]

Why not just use CLAUDE.md? CLAUDE.md is rules. .startup.md is state. Rules change rarely β€” you write them once and they compound over time. State changes constantly β€” current branch, active features, open findings. Mixing them means Claude re-reads your entire rulebook to find out what branch you are on. Separating them means each file stays small, focused, and cheap to load.

Known behaviour: The SessionStart hook with source: "startup" has a known intermittent bug in some Claude Code versions where context injection is silently skipped on brand new sessions. It works reliably on /clear and compaction. Run /clear at the start of any session where you need guaranteed context injection. This is an upstream Claude Code issue being tracked.

MDD Dashboard β€” Terminal TUI

The mdd package is a standalone terminal dashboard for MDD workspaces. Run it inside any project with a .mdd/ folder to get a real-time, interactive view of your workspace health β€” without leaving VS Code.

MDD Dashboard β€” terminal TUI showing feature doc list on the left, doc content on the right, and live drift counts across the top
npm install -g mdd-tui

Then inside any project with a .mdd/ folder:

mdd              # opens the interactive TUI
mdd dashboard    # same
mdd status       # same β€” all three open the dashboard

Left Panel

INITIATIVES (collapsible tree, shown when .mdd/initiatives/ exists) β†’ feature docs β†’ audit reports β†’ dep graph. ↑↓ to navigate, Enter to expand an initiative.

Right Panel

Initiative overview & wave detail, or full doc/audit content with drift chips, frontmatter badges, and scrollable markdown. Press β†’ to focus, ↑↓ to scroll, ← to return.

Status Bar

Live counts: docs Β· in-sync Β· drifted Β· broken Β· untracked Β· issues Β· audits Β· initiatives Β· active waves. Updated on every r refresh.

Drift Detection

Auto-runs git log against each doc's last_synced field. Docs whose source_files changed since last sync are marked ⚠️ drifted. Stale waves (version mismatch) flagged separately.

Keyboard shortcuts: ↑/k Β· ↓/j navigate Β· β†’/l/Enter focus right or expand initiative Β· ←/h/Esc back Β· i jump to first initiative Β· PgUp/PgDn scroll page Β· r refresh Β· q quit

npm: mdd-tui Β· GitHub

Ops Mode NEW

Document-first deployments β€” the same discipline MDD brings to features, now applied to ops tasks. Runbooks replace improvised deploys. Every region is gated. If canary fails, primary is never touched.

What Ops Mode fixes: MDD's original flaw β€” deployment and ops tasks had no documentation home. They fell into Build Mode or were skipped entirely. Ops Mode gives deployments the same document-first discipline as features. Write the runbook once; /mdd runop executes it every time.

The Four Commands

/mdd ops <description>

Create a new deployment runbook. First asks: global (~/.claude/ops/) or project-scoped (.mdd/ops/)? Interviews you about services, regions, health checks, rollback criteria, and deployment strategy. Produces a structured YAML-frontmatter runbook that runop can execute.

/mdd runop <slug>

Execute a runbook end-to-end: pre-flight health check β†’ canary-gated region deploy β†’ post-flight verify. Checks project-local first, then global. Reads the ops doc as the source of truth. If any gate fails, execution stops β€” the next region is never touched.

/mdd update-op <slug>

Edit an existing runbook. Checks project-local first, then global. Updates services, regions, health endpoints, rollback criteria, or deployment strategy. Re-validates the runbook structure after editing.

/mdd ops list

Show all runbooks β€” global and project-scoped β€” in a unified view. Displays slug, scope, platform, environments, and status so you can see everything available at a glance.

Global vs Project Scope

/mdd ops asks scope as its very first question. The answer controls where the runbook is stored and how it is shared.

Scope Location Available Use for
Global ~/.claude/ops/<slug>.md All projects Docker Hub login, DNS updates, Vercel deploys, reusable infrastructure tasks
Project .mdd/ops/<slug>.md This project only Service-specific deploys, project env vars, region-specific image names
Global scope note: Global ops cannot read project-local .env variables or project paths. They have access to ~/.env globals only. If your runbook needs DOCKER_HUB_TOKEN or other global secrets, store them in ~/.env and reference them there.
Collision guard: Global namespace is authoritative. If a global op named docker-hub-push already exists, you cannot create a project op with the same slug. This is a hard stop β€” no silent shadowing. Rename one of them to avoid ambiguity.

Listing All Runbooks

/mdd ops list shows all runbooks across both scopes in a unified view:

Ops Runbooks
────────────────────────────────────────────────────────────

Global (~/.claude/ops/)
  docker-hub-login       docker-hub    all projects    complete
  dns-cloudflare         manual        all projects    draft

Project (.mdd/ops/)
  rulecatch-dokploy      dokploy       staging, prod   in_progress
  api-rollback           manual        production      draft

4 runbooks total (2 global, 2 project)
Run /mdd runop <slug> to execute any runbook.

The Runbook Concept

A runbook is a structured ops document in .mdd/ops/ with YAML frontmatter declaring services, regions, deployment order, health check endpoints, and gate behaviour. It is the single source of truth for a deployment. /mdd runop reads it and executes it β€” you do not hand-craft the sequence each time.

Write once, runs every time. Once a runbook exists, every future deployment of that service runs through the same documented sequence, with the same pre-flight checks, the same canary gate, and the same post-flight verification. Nothing falls through the cracks because someone forgot a step.

Canary Deployment Pattern

Ops Mode enforces a canary-first deployment model. Regions are ordered by deploy_order in the runbook frontmatter. The canary region always deploys first β€” only if all its services pass the health gate does the primary region proceed.

πŸ”
Pre-flight Health-check all regions before any deploy begins
🐦
Canary Deploy Deploy to canary region first (deploy_order: 1)
🚦
Canary Gate All services must be healthy before advancing
πŸš€
Primary Deploy Only then deploy to primary region (deploy_order: 2)
βœ…
Post-flight Verify all regions healthy, update runbook frontmatter

If the canary gate fails β€” any service unhealthy after deploy β€” the primary region is never touched. It is still running the old version. You can redeploy to canary, skip that region, or abort entirely. The gate behaviour is configurable: stop (default), skip_region, or rollback.

Pre-flight Health Check

Before any deployment begins, /mdd runop checks the current health of all services across all regions. If a service is already failing before you deploy, you know upfront β€” not after the deploy makes it worse. The pre-flight table surfaces this clearly and prompts for a decision:

Pre-flight Health Check β€” rulecatch-dokploy
──────────────────────────────────────────────────
                     eu-west (canary)  us-east (primary)
api                  βœ“ healthy         βœ“ healthy
dashboard            βœ— failing         βœ“ healthy
worker               βœ“ healthy         βœ“ healthy

dashboard is failing in eu-west. Redeploy, skip, or abort?

Canary Gate Output

After the canary deploy completes, /mdd runop re-checks every service in the canary region. The gate output shows exactly which image each service is running and its health status:

── eu-west (canary) β€” gate check ──────────────
api         βœ“ healthy  (rulecatch-api-eu:latest)
dashboard   βœ“ healthy
worker      βœ“ healthy
Gate: PASSED βœ“ β€” advancing to us-east (primary)

Multi-Region, Multi-Image Support

Each service can have a different Docker image name per region. This supports regional image registries, blue-green strategies, or teams that maintain separate EU and US image builds. Per-region health status is tracked in the runbook frontmatter so the dashboard can show the last-known state of every region at a glance.

Per-Region Images

Each service declares its image name per region in the runbook frontmatter. runop reads the correct image for each region automatically β€” no manual substitution.

Health Status Tracking

After each runop execution, the runbook frontmatter is updated with the last-known health status per region and service. /mdd status can surface this in the startup context.

Deployment Strategies

deployment_strategy: sequential deploys regions one at a time with gates between each. deployment_strategy: parallel deploys non-canary regions simultaneously after the canary gate passes.

Gate Behaviour

gate_on_fail: stop halts execution (default). skip_region logs the failure and continues to remaining regions. rollback triggers the runbook’s defined rollback procedure before stopping.

Directory Structure

Project runbooks live in .mdd/ops/. Global runbooks live in ~/.claude/ops/ alongside your other global Claude config:

# Project-scoped runbooks (this project only)
.mdd/
β”œβ”€β”€ docs/                          # Feature documentation
β”œβ”€β”€ ops/                           # Project deployment runbooks
β”‚   β”œβ”€β”€ rulecatch-dokploy.md       # Multi-region Dokploy deploy runbook
β”‚   └── api-rollback.md            # Emergency rollback runbook
β”œβ”€β”€ initiatives/
β”œβ”€β”€ waves/
└── audits/

# Global runbooks (available in every project)
~/.claude/
β”œβ”€β”€ commands/                      # Global slash commands
β”œβ”€β”€ skills/                        # Global skills
β”œβ”€β”€ ops/                           # Global deployment runbooks ← NEW
β”‚   β”œβ”€β”€ docker-hub-login.md        # Reusable Docker Hub auth runbook
β”‚   └── dns-cloudflare.md          # DNS update runbook (any project)
└── CLAUDE.md

Project runbooks are gitignored by default alongside the rest of .mdd/ β€” they contain environment-specific configuration (region URLs, health endpoints, image names) that belongs in your local workspace, not version control. Global runbooks persist in your home directory and are never project-specific.

What Is This?

This is a scaffold template, not a runnable application. It provides the infrastructure (commands, hooks, skills, agents, documentation templates) that makes Claude Code dramatically more effective. You use it to create projects, not run it directly.

Three Ways to Use It

A. Scaffold a New Project

The most common path. Run /new-project my-app clean (or default) to create a new project directory with all Claude Code tooling pre-configured. Run /quickstart for a guided walkthrough.

B. Convert an Existing Project

Already have a project? Run /convert-project-to-starter-kit ~/projects/my-app to non-destructively merge all starter kit infrastructure into it. Preserves everything you have, adds what's missing. Undo with git revert HEAD.

C. Customize the Template

Clone this repo and modify the commands, hooks, skills, and rules to match your team's standards. Then use your customized version as the source for /new-project.

What NOT to do: Don't clone this repo and run pnpm dev expecting a working app. This is the template that creates apps β€” it's not an app itself. Start with option A above.

Learning Path

Progress through these phases at your own pace. Each builds on the previous one.

Two workflows, one toolkit. The starter kit supports two development approaches:
β€’ Classic β€” /review, /commit, /create-api, /create-e2e (individual commands, you drive)
β€’ MDD β€” /mdd (structured Document β†’ Test β†’ Code workflow, Claude drives with your approval)
Both use the same hooks, rules, and quality gates. MDD adds structured documentation and audit capabilities on top. Learn more about MDD β†’
1

Initial Setup

5 minutes

  • /install-global
  • /new-project
  • cd my-app
  • /setup
β†’
2

Build Features

  • /mdd <feature> MDD
  • /review
  • /commit
  • /create-api
β†’
3

Quality & Testing

  • /mdd audit MDD
  • /mdd scan MDD
  • /create-e2e
  • /test-plan
β†’
4

Deployment

  • /optimize-docker
  • /security-check
  • deploy
β†’
5

Advanced

  • /refactor
  • /what-is-my-ai-doing
  • /worktree
  • custom rules

First 5 Minutes

/install-global                    # One-time: install global Claude config
/new-project my-app clean          # Scaffold a project (or: default for full stack)
cd ~/projects/my-app               # Enter your new project
/setup                             # Configure .env interactively
pnpm install && pnpm dev           # Start building

First Feature (MDD Workflow)

/mdd user authentication           # Claude analyzes existing code, interviews you,
                                    # writes docs, generates test skeletons, presents
                                    # a plan, then builds

Use /help to see all 27 commands at any time.

Quick Start

1

Clone and Customize

# 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
2

Set Up Global Config (One Time)

# Run the install command β€” smart merges into existing config
/install-global

This installs global CLAUDE.md rules, settings.json hooks, and enforcement scripts into ~/.claude/. If you already have a global config, it merges without overwriting.

Say yes to the MDD global install prompt. This copies /mdd to ~/.claude/commands/ so it’s available in every project β€” no per-project setup required. Update the starter kit once and all projects pick up the new /mdd version automatically. Running /mdd for the first time in any project auto-creates the .mdd/ structure.

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/check-rulecatch.sh ~/.claude/hooks/
3

Customize for Your Project

  1. Run /setup β€” Interactive .env configuration (database, GitHub, Docker, analytics)
  2. Edit CLAUDE.md β€” Update port assignments, add your specific rules
  3. Run /diagram all β€” Auto-generate architecture, API, database, and infrastructure diagrams
  4. Edit CLAUDE.local.md β€” Add your personal preferences

StrictDB works out of the box β€” just pnpm add strictdb and set STRICTDB_URI in your .env. Built-in sanitization and guardrails run on all inputs: safe operators ($gte, $in, $regex, etc.) pass through while dangerous operators ($where, $function) are stripped. Supports MongoDB, PostgreSQL, MySQL, MSSQL, SQLite, and Elasticsearch. See the StrictDB section for details.

4

Start Building

claude

That's it. Claude Code now has battle-tested rules, deterministic hooks, slash commands, and documentation templates all ready to go.

Troubleshooting

Hooks Not Firing

Verify .claude/settings.json is valid JSON. Check that hook file paths are correct and executable. Restart your Claude Code session β€” hooks are loaded at session start.

pnpm dev Fails or Does Nothing

This is a scaffold template, not a runnable app. Use /new-project my-app to create a project first, then run pnpm dev inside that project.

Database Connection Errors

Run /setup to configure your .env with a valid connection string. Check that STRICTDB_URI is set and your IP is whitelisted (if using a cloud database like MongoDB Atlas).

/install-global Reports Conflicts

Normal behavior. The command uses smart merge β€” it keeps your existing sections and only adds what's missing. Check the report output for details.

Port Already in Use

Run lsof -i :PORT to find the process, then kill -9 PID. Or kill all test ports at once: pnpm test:kill-ports

E2E Tests Timing Out

Kill stale processes: pnpm test:kill-ports. Run headed to debug: pnpm test:e2e:headed. Check playwright.config.ts webServer config.

RuleCatch Not Monitoring

Free monitor mode requires no setup. Open a separate terminal and run pnpm ai:monitor (or npx @rulecatch/ai-pooler monitor --no-api-key). For full violation tracking, sign up at rulecatch.ai and run npx @rulecatch/ai-pooler init --api-key=YOUR_KEY --region=us.

Project Structure

project/
β”œβ”€β”€ CLAUDE.md                    # Project instructions (customize this!)
β”œβ”€β”€ CLAUDE.local.md              # Personal overrides (gitignored)
β”œβ”€β”€ .claude/
β”‚   β”œβ”€β”€ settings.json            # Hooks configuration
β”‚   β”œβ”€β”€ commands/
β”‚   β”‚   β”œβ”€β”€ help.md              # /help β€” list all commands, skills, and agents
β”‚   β”‚   β”œβ”€β”€ quickstart.md        # /quickstart β€” interactive first-run walkthrough
β”‚   β”‚   β”œβ”€β”€ 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/
β”‚   β”‚   β”œβ”€β”€ install-mdd.md       # /install-mdd β€” install MDD workflow into any project
β”‚   β”‚   β”œβ”€β”€ diagram.md           # /diagram β€” generate diagrams from actual code
β”‚   β”‚   β”œβ”€β”€ set-project-profile-default.md # /set-project-profile-default β€” set default profile
β”‚   β”‚   β”œβ”€β”€ add-project-setup.md  # /add-project-setup β€” create a named profile
β”‚   β”‚   β”œβ”€β”€ projects-created.md   # /projects-created β€” list all created projects
β”‚   β”‚   β”œβ”€β”€ remove-project.md     # /remove-project β€” remove a project from registry
β”‚   β”‚   β”œβ”€β”€ convert-project-to-starter-kit.md # /convert-project-to-starter-kit β€” merge into existing project
β”‚   β”‚   β”œβ”€β”€ update-project.md      # /update-project β€” update a project with latest starter kit
β”‚   β”‚   β”œβ”€β”€ add-feature.md         # /add-feature β€” add capabilities post-scaffolding
β”‚   β”‚   └── show-user-guide.md    # /show-user-guide β€” open the User Guide in browser
β”‚   β”œβ”€β”€ 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
β”‚       β”œβ”€β”€ check-rybbit.sh      # PreToolUse: block deploy without Rybbit
β”‚       β”œβ”€β”€ check-branch.sh      # PreToolUse: block commits on main
β”‚       β”œβ”€β”€ check-ports.sh       # PreToolUse: block if port in use
β”‚       β”œβ”€β”€ check-e2e.sh         # PreToolUse: block push without E2E tests
β”‚       β”œβ”€β”€ lint-on-save.sh      # PostToolUse: lint after writes
β”‚       β”œβ”€β”€ verify-no-secrets.sh # Stop: check for secrets
β”‚       β”œβ”€β”€ check-rulecatch.sh   # Stop: report RuleCatch violations
β”‚       └── check-env-sync.sh    # Stop: warn on .env/.env.example drift
β”œβ”€β”€ project-docs/
β”‚   β”œβ”€β”€ ARCHITECTURE.md          # System overview (authoritative)
β”‚   β”œβ”€β”€ INFRASTRUCTURE.md        # Deployment details
β”‚   └── DECISIONS.md             # Architectural decision records
β”œβ”€β”€ docs/                        # GitHub Pages site
β”‚   └── user-guide.html          # Interactive User Guide (HTML)
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ handlers/                # Business logic
β”‚   β”œβ”€β”€ adapters/                # External service adapters
β”‚   └── 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
β”œβ”€β”€ USER_GUIDE.md                # Comprehensive User Guide (Markdown)
β”œβ”€β”€ .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

Key Concepts

Defense in Depth V3

Three layers of protection working together:

  1. CLAUDE.md rules β€” Behavioral suggestions (weakest)
  2. Hooks β€” Guaranteed to run, stronger than rules, but not bulletproof
  3. Git safety β€” .gitignore as last line of defense (strongest)

One Task, One Chat V1–V3

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.

Quality Gates V1/V2

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.

MCP Tool Search V4

With 10+ MCP servers, tool descriptions consume 50–70% of context. Tool Search lazy-loads on demand, saving 85% of context.

Plan First, Code Second V5

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.”

CLAUDE.md Is Team Memory

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.

Never Work on Main

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.

Windows? Use WSL Mode

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.

Every Command Enforces the Rules

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.

TypeScript Is Non-Negotiable V5

Types are specs that tell Claude what functions accept and return. Without types, Claude guesses β€” and guesses become runtime errors.

CLAUDE.md β€” The Rulebook

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:

Rule 0

NEVER Publish Sensitive Data

  • NEVER commit passwords, API keys, tokens, or secrets to git/npm/docker
  • NEVER commit .env files β€” ALWAYS verify .env is in .gitignore
  • Before ANY commit: verify no secrets are included
Rule 1

TypeScript Always

  • ALWAYS use TypeScript for new files (strict mode)
  • NEVER use any unless absolutely necessary and documented why
  • When editing JavaScript files, convert to TypeScript first
  • Types are specs β€” they tell you what functions accept and return
Rule 2

API Versioning

CORRECT: /api/v1/users
WRONG:   /api/users

Every API endpoint MUST use /api/v1/ prefix. No exceptions.

Rule 3

Database Access β€” StrictDB Only

  • NEVER create direct database connections β€” always use StrictDB
  • ALWAYS use StrictDB for all database operations
  • Built-in sanitization and guardrails: safe operators pass through, dangerous operators ($where, $function) stripped. Use { trusted: true } for non-standard operators
  • Supports MongoDB, PostgreSQL, MySQL, MSSQL, SQLite, and Elasticsearch
  • One connection pool. One place to change. One place to mock.
Rule 4

Testing β€” Explicit Success Criteria

// 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!
Rule 5

NEVER Hardcode Credentials

ALWAYS use environment variables. NEVER put API keys, passwords, or tokens directly in code. NEVER hardcode connection strings β€” use STRICTDB_URI from .env.

Rule 6

ALWAYS Ask Before Deploying

NEVER auto-deploy, even if the fix seems simple. NEVER assume approval β€” wait for explicit confirmation.

Rule 7

Quality Gates

  • 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)
Rule 9

Git Workflow β€” Auto-Branch on Main

  • 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 /worktree for 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 = false in claude-mastery-project.conf
Rule 8

Parallelize Independent Awaits

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
Rule 10

Docker Push Gate β€” Local Test First

Disabled by default. When enabled, NO docker push is allowed until the image passes local verification:

  1. Build the image
  2. Run the container locally
  3. Verify it doesn't crash (still running after 5s)
  4. Health endpoint returns 200
  5. No fatal errors in logs
  6. Clean up, then push

Enable with docker_test_before_push = true in claude-mastery-project.conf. Applies to all commands that push Docker images.

When Something Seems Wrong

The CLAUDE.md also includes a β€œCheck Before Assuming” pattern that prevents Claude from jumping to conclusions:

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

Fixed Service Ports

Port conflicts are one of the most common problems in multi-service development. The CLAUDE.md locks them down:

ServiceDev PortTest Port
Website30004000
API30014010
Dashboard30024020

Hooks β€” Stronger Than Rules

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 that behavior will be followed.

PreToolUse

block-secrets.py

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)
PreToolUse

check-rybbit.sh

Runs before any deployment command (docker push, vercel deploy, dokploy). If the project has analytics = rybbit in claude-mastery-project.conf, verifies that NEXT_PUBLIC_RYBBIT_SITE_ID is set in .env with a real value. Blocks with a link to app.rybbit.io if missing. Skips projects that don't use Rybbit.

PreToolUse

check-branch.sh

Runs before any git commit. If auto-branch is enabled (default: true) and you're on main/master, blocks the commit and tells Claude to create a feature branch first. Respects the auto_branch setting in claude-mastery-project.conf.

PreToolUse

check-ports.sh

Runs before dev server commands. Detects the target port from -p, --port, PORT=, or known script names (dev:website→3000, dev:api→3001, etc.). If the port is already in use, blocks and shows the PID + kill command.

PreToolUse

check-e2e.sh

Runs before git push to main/master. Checks for real .spec.ts or .test.ts files in tests/e2e/ (excluding the example template). Blocks push if no E2E tests exist.

PostToolUse

lint-on-save.sh

Runs after Claude writes or edits a file. Automatically checks TypeScript compilation, ESLint, or Python linting depending on file extension. Kept fast (<5 seconds) so Claude doesn't skip it.

case "$EXTENSION" in
    ts|tsx)
        # TypeScript β€” run type check
        npx tsc --noEmit --pretty "$FILE_PATH" 2>&1 | head -20
        ;;
    js|jsx)
        # JavaScript β€” run eslint
        npx eslint "$FILE_PATH" 2>&1 | head -20
        ;;
    py)
        # Python β€” run ruff or flake8
        ruff check "$FILE_PATH" 2>&1 | head -20
        ;;
esac
Stop

verify-no-secrets.sh

Runs 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"
fi
Stop

check-rulecatch.sh

Runs 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.

# Run RuleCatch violation check
RESULT=$(npx @rulecatch/ai-pooler@latest check --quiet --format summary 2>/dev/null)

if [ -n "$RESULT" ] && [ "$RESULT" != "0 violations" ]; then
    echo "πŸ“‹ RuleCatch: $RESULT" >&2
    echo "   Run 'pnpm ai:monitor' for details." >&2
fi
Stop

check-env-sync.sh

Runs when Claude finishes a turn. Compares key names (never values) between .env and .env.example. If .env has keys that .env.example doesn't document, prints a warning so other developers know those variables exist. Informational only β€” never blocks.

Hook Configuration

Hooks are wired up in .claude/settings.json. Each hook type fires at a different point in Claude's lifecycle:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Edit|Write",
        "hooks": [{ "type": "command", "command": "python3 .claude/hooks/block-secrets.py" }]
      },
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "bash .claude/hooks/check-rybbit.sh" },
          { "type": "command", "command": "bash .claude/hooks/check-branch.sh" },
          { "type": "command", "command": "bash .claude/hooks/check-ports.sh" },
          { "type": "command", "command": "bash .claude/hooks/check-e2e.sh" }
        ]
      }
    ],
    "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/check-rulecatch.sh" },
        { "type": "command", "command": "bash .claude/hooks/check-env-sync.sh" }
      ]
    }]
  }
}

Slash Commands β€” On-Demand Tools

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.

Try it now: See everything your AI does in real-time β†’ run pnpm ai:monitor in a separate terminal (free, no API key needed)

/help

Lists every command, skill, and agent in the starter kit, grouped by category: Getting Started, Project Scaffold, Code Quality, Development, Infrastructure, and Monitoring. Also shows skill triggers and agent descriptions. Run /help anytime to see what's available.

/quickstart

Interactive first-run walkthrough for new users. Checks if global config is installed, asks for a project name and profile preference (clean vs default), then walks you through the first 5 minutes: scaffolding, setup, first dev server, first review, first commit.

/diagram

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.

/install-global Recommended for MDD

One-time setup that makes /mdd available in every project on your machine. Say yes to the MDD prompt.

Why global? Install once β†’ use everywhere. Update the starter kit once β†’ all projects automatically get the latest /mdd on the next session. When you run /mdd for the first time in any project, it auto-creates the .mdd/ structure (docs, audits, startup file, gitignore entry) β€” no separate /install-mdd needed per project.

  • 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, and check-rulecatch.sh to ~/.claude/hooks/
  • MDD global install β€” installs @thedecipherist/mdd npm package and deploys all MDD commands to ~/.claude/commands/ (say yes to this prompt)

Reports exactly what was added, skipped, and merged. Your existing config is never overwritten.

Already set up? Update MDD only:

/install-global mdd    # updates @thedecipherist/mdd npm package only β€” skips everything else

Use this whenever a new MDD version is available and you want to update the global commands without re-running the full setup.

/install-mdd [path]

Install the MDD workflow into a specific project explicitly β€” use this for team setups or when you want the structure in place before the first run. If you’ve installed MDD globally, /mdd bootstraps itself and you don’t need this.

  • Scaffolds .mdd/ directory structure (requires @thedecipherist/mdd npm package)
  • Scaffolds .mdd/docs/, .mdd/audits/, and .mdd/.startup.md
  • Adds .mdd/audits/ to .gitignore (audit reports are ephemeral)
  • Works on any stack β€” pass a path or run from within the target project

/setup

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 β€” StrictDB per region (STRICTDB_URI_US, STRICTDB_URI_EU)
  • Deployment β€” Dokploy on Hostinger VPS per region (IP, API key, app ID, webhook token)
  • Docker β€” Hub username, image name, region tagging (:latest for US, :eu for 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.

/show-user-guide

Opens the comprehensive User Guide in your browser. Includes step-by-step tutorials, command deep dives, hook explanations, database cookbook, and troubleshooting. Tries the GitHub Pages URL first, falls back to the local file.

/what-is-my-ai-doing

Free monitor mode β€” no API key, no account, no setup. Just open a separate terminal and run it.

Launches the RuleCatch AI-Pooler live monitor in a separate terminal. See everything your AI is doing in real time:

  • Every tool call (Read, Write, Edit, Bash)
  • Token usage and cost per turn
  • Which files are being accessed
  • Cost per session
# Open a separate terminal and run this while Claude works
npx @rulecatch/ai-pooler monitor --no-api-key

Zero token overhead β€” runs completely outside Claude's context. Also available as pnpm ai:monitor.

Want more? With a RuleCatch.AI API key you also get violation tracking, dashboards, and the MCP server. See Monitor Your Rules.

/review

Systematic code review against a 7-point checklist:

  1. Security β€” OWASP Top 10, no secrets in code
  2. Types β€” No any, proper null handling
  3. Error Handling β€” No swallowed errors
  4. Performance β€” No N+1 queries, no memory leaks
  5. Testing β€” New code has explicit assertions
  6. Database β€” Using StrictDB
  7. API Versioning β€” All endpoints use /api/v1/

Issues are reported with severity (Critical / Warning / Info), file:line references, and suggested fixes.

/commit

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.

/test-plan

Generates a structured test plan for any feature with:

  • Prerequisites and environment setup
  • Happy path scenarios with specific expected outcomes
  • Error cases and edge cases (empty, null, max values, concurrency)
  • Pass/fail criteria table
  • Sign-off tracker

/security-check

Scans the project for security vulnerabilities:

  • Secrets in code (API keys, AWS keys, credential URLs)
  • .gitignore coverage verification
  • Sensitive files tracked by git
  • .env handling audit
  • Dependency vulnerability scan (npm audit)

/progress

Checks the actual filesystem state and reports project status β€” source file counts by type, test coverage, recent git activity, and prioritized next actions.

/architecture

Reads project-docs/ARCHITECTURE.md and displays the system overview, data flow diagrams, and service responsibility maps. If docs don't exist, scaffolds them.

/worktree

Creates an isolated git worktree + branch for a task:

/worktree add-auth          # β†’ task/add-auth branch
/worktree feat/new-dashboard # β†’ uses prefix as-is

Each task gets its own branch and its own directory. Main stays untouched. If Claude screws something up, delete the branch β€” zero risk. Enables running multiple Claude sessions in parallel without conflicts.

When done: merge into main (or open a PR), then git worktree remove.

/optimize-docker

Audits your Dockerfile against 12 production best practices:

  1. Multi-stage builds β€” mandatory, no exceptions
  2. Layer caching β€” COPY package.json before source
  3. Alpine base images β€” 7x smaller than full images
  4. Non-root user β€” drop privileges
  5. .dockerignore β€” must exclude .env, .git, node_modules
  6. Frozen lockfile β€” deterministic installs
  7. Health checks β€” Docker knows if app is alive
  8. No secrets in build args β€” runtime env only
  9. Pin versions β€” no :latest tags

Generates an optimized Dockerfile, verifies .dockerignore, and reports image size estimate with before/after comparison. When docker_test_before_push = true in conf, blocks docker push until the image passes local verification (build, run, health check, no crash).

/create-e2e

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 (URL assertion, visibility assertion, data assertion, error case, no TODOs) before finishing.

/create-api

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 StrictDB with shared pool, auto-sanitized inputs, pagination (max 100), registered indexes, and /api/v1/ prefix. Pass --no-db to skip database integration.

/refactor

Audit + refactor any file against every rule in CLAUDE.md:

  1. Branch check β€” verifies you're not on main (suggests /worktree)
  2. File size β€” >300 lines = must split
  3. Function size β€” >50 lines = must extract
  4. TypeScript β€” no any, explicit types, strict mode
  5. Import hygiene β€” no barrel imports, proper import type
  6. Error handling β€” no swallowed errors, proper logging
  7. Database access β€” StrictDB only (import from 'strictdb')
  8. API routes β€” /api/v1/ prefix
  9. Promise.all β€” parallelize independent awaits
  10. Security + dead code β€” no secrets, no unused code

Presents a named-step plan before making any changes. Splits files by type (types β†’ src/types/, validation β†’ colocated, helpers β†’ colocated). Updates all imports across the project. Runs RuleCatch after completion.

/refactor src/handlers/users.ts
/refactor src/server.ts --dry-run    # report only, no changes

/new-project

Full project scaffolding with profiles or shorthand params:

/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-site
/new-project my-api go                    # Go API with Gin, StrictDB, Docker
/new-project my-api go chi postgres       # Go with Chi, PostgreSQL
/new-project my-cli go cli                # Go CLI with Cobra
/new-project my-app vue                    # Vue 3 SPA with Tailwind
/new-project my-app nuxt                   # Nuxt full-stack with StrictDB, Docker
/new-project my-app sveltekit              # SvelteKit full-stack
/new-project my-api python-api             # FastAPI with PostgreSQL, Docker
/new-project my-app django                 # Django full-stack

clean β€” All Claude infrastructure (commands, skills, agents, hooks, project-docs, tests templates) with zero coding opinions. No TypeScript enforcement, no port assignments, no StrictDB rules, no quality gates. Your project, your rules β€” Claude just works.

go β€” Go project scaffolding with standard layout (cmd/, internal/), Gin router, Makefile builds, golangci-lint, table-driven tests, multi-stage Docker with scratch base (5-15MB images). Supports Gin, Chi, Echo, Fiber, or stdlib net/http.

default and other profiles β€” Full opinionated scaffolding with project type, framework, SSR, hosting (Dokploy/Vercel/static), package manager, database (via StrictDB), extras (Tailwind, Prisma, Docker, CI), and MCP servers. Includes mandatory SEO for web projects and Dokploy deployment scripts with multi-region support.

vue / nuxt / svelte / sveltekit / angular β€” Frontend framework scaffolding with CLI scaffold + starter kit overlay. Each gets framework-specific CLAUDE.md rules (Composition API for Vue, Runes for Svelte, Standalone Components for Angular).

python-api / django / flask β€” Python project scaffolding with FastAPI/Django/Flask, pytest, ruff linter, virtual environment, and multi-stage Docker. Full type hints enforced.

Use claude-mastery-project.conf profiles to save your preferred stack.

/set-project-profile-default

Sets the default profile for /new-project. Accepts any profile name: clean, default, go, vue, python-api, etc. Also supports shorthand: /set-project-profile-default mongo next tailwind docker creates a [user-default] profile with those settings.

/add-project-setup

Interactive wizard to create a named profile in claude-mastery-project.conf. Asks about language, framework, database (via StrictDB), hosting, and more. Use with /new-project my-app <profile-name>.

/projects-created

Lists every project scaffolded by /new-project, with creation date, profile, language, framework, database (StrictDB), and location. Checks which projects still exist on disk and marks missing ones. Data stored in ~/.claude/starter-kit-projects.json.

/remove-project

Removes a project from the starter kit registry and optionally deletes its files from disk. Shows project details, asks for confirmation, checks for uncommitted git changes before deletion. Use /remove-project my-app or run without arguments to pick from a list.

/convert-project-to-starter-kit

Merges all starter kit infrastructure into an existing project without destroying anything. Creates a safety commit, detects language and existing Claude setup, asks how to handle conflicts, then copies commands, hooks, skills, agents, merges CLAUDE.md sections, deep-merges settings.json, and adds infrastructure files. Registers the project in ~/.claude/starter-kit-projects.json. Undo with git revert HEAD.

/convert-project-to-starter-kit ~/projects/my-app
/convert-project-to-starter-kit ~/projects/my-app --force

/update-project

Updates an existing starter-kit project with the latest commands, hooks, skills, agents, and rules. Smart merge β€” replaces starter kit files with newer versions while preserving any custom files. Shows a diff report before applying, creates a safety commit for easy undo.

/update-project              # Pick from registered projects
/update-project --force      # Skip confirmation prompts

/add-feature <name>

Add capabilities (StrictDB, Docker, testing, etc.) to an existing project after scaffolding. Idempotent β€” safely updates already-installed features. Maintains a feature manifest (.claude/features.json) so /update-project can sync feature files too.

/add-feature strictdb         # Add StrictDB + query system
/add-feature vitest playwright # Add both test frameworks
/add-feature --list           # Show all available features

Supported Technologies

This starter kit works with any language, framework, or database. Use /new-project my-app clean for zero opinions, or pick a profile that matches your stack.

Languages & Frameworks

CategoryTechnologiesNotes
LanguagesNode.js/TypeScript, Go, PythonFull scaffolding support
FrontendReact, Vue 3, Svelte, SvelteKit, Angular, Next.js, Nuxt, AstroCLI scaffold + CLAUDE.md rules
Backend (Node.js)Fastify, Express, HonoAPI scaffolding with /create-api
Backend (Go)Gin, Chi, Echo, Fiber, stdlibStandard layout cmd/internal/
Backend (Python)FastAPI, Django, FlaskAsync, Pydantic, pytest
DatabaseMongoDB, PostgreSQL, MySQL, MSSQL, SQLite, ElasticsearchStrictDB + StrictDB-MCP
HostingDokploy, Vercel, StaticDeploy scripts + Docker
TestingVitest, Playwright, pytest, Go testFramework-appropriate setup
CSSTailwind CSS + ClassMCP + ClasspressoClassMCP (MCP) + Classpresso (post-build) auto-included in CSS profiles

Recommended Stacks

Use CaseStackProfile
SPA DashboardVite + React + Fastify + StrictDBdefault
REST API (Node.js)Fastify + PostgreSQLapi + postgres
Go MicroserviceGin + PostgreSQLgo + postgres
Python APIFastAPI + PostgreSQLpython-api
Vue SPAVue 3 + Vite + Tailwindvue
Nuxt Full-StackNuxt + StrictDB + Dockernuxt
SvelteKit Full-StackSvelteKit + StrictDB + Dockersveltekit
Angular AppAngular + Tailwindangular
Django Web AppDjango + PostgreSQL + Dockerdjango
Content SiteAstro or SvelteKitstatic-site
AI goodies onlyAny β€” you chooseclean

Skills β€” Triggered Expertise

Skills are context-aware templates that activate automatically when Claude detects relevant keywords in your conversation. Unlike slash commands (which you invoke explicitly with /command), skills load themselves when needed.

What Triggers Skills?

Claude monitors your conversation for specific keywords. When it detects a match, it loads the relevant skill template β€” giving Claude structured instructions for that specific task. You don't need to do anything special.

SkillTrigger KeywordsWhat It Does
Code Reviewreview, audit, check code, security reviewLoads a systematic 7-point review checklist with severity ratings
Create Servicecreate service, new service, scaffold serviceScaffolds a microservice with server/handlers/adapters pattern

How to Activate Skills

You don't β€” just use natural language. Say things like:

  • β€œReview this file for security issues” β†’ Code Review skill activates
  • β€œAudit the authentication module” β†’ Code Review skill activates
  • β€œCreate a new payment service” β†’ Create Service skill activates
  • β€œScaffold a notification service” β†’ Create Service skill activates

Skills vs Commands

SkillsCommands
How to useAutomatic β€” just use natural languageExplicit β€” type /command
When they loadWhen Claude detects trigger keywordsWhen you invoke them
Exampleβ€œReview this code”/review
Best forOrganic, conversational workflowsDeliberate, specific actions

Both skills and commands can cover similar ground (e.g., code review). Skills are more natural; commands are more predictable. Use whichever fits your workflow.

Code Review Skill

Triggers: review, audit, check code, security review

A systematic review checklist that covers 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 (StrictDB, API versioning, service separation).

Each issue is reported with severity, location, fix, and why it matters.

Create Service Skill

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 adapters                         β”‚
β”‚  β†’ Third-party APIs, etc.                            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Includes package.json, tsconfig.json, entry point with error handlers, health check endpoint, and a post-creation verification checklist.

Custom Agents β€” Specialist Subagents

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.

Code Reviewer Agent

Tools: Read, Grep, Glob (read-only)

β€œYou are a senior code reviewer. Your job is to find real problems β€” not nitpick style.”

Priority order:

  1. Security β€” secrets in code, injection vulnerabilities, auth bypasses
  2. Correctness β€” logic errors, race conditions, null pointer risks
  3. Performance β€” N+1 queries, memory leaks, missing indexes
  4. Type Safety β€” any usage, missing null checks, unsafe casts
  5. Maintainability β€” dead code, unclear naming (lowest priority)

If the code is good, it says so β€” it doesn't invent issues to justify its existence.

Test Writer Agent

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 vague

StrictDB β€” Unified Database Driver

The starter kit uses StrictDB β€” a production-grade unified database driver (npm package) supporting MongoDB, PostgreSQL, MySQL, MSSQL, SQLite, and Elasticsearch. It enforces every best practice that prevents the most common database failures in AI-assisted development.

The Absolute Rule

ALL database access goes through StrictDB. No exceptions. Never create direct database clients. Never import raw database drivers in business logic.

// CORRECT β€” import from StrictDB
import { queryOne, insertOne, updateOne } from 'strictdb';

// WRONG β€” NEVER do this
import { MongoClient } from 'mongodb';     // FORBIDDEN β€” use StrictDB
import { Pool } from 'pg';                 // FORBIDDEN β€” use StrictDB

Reading Data β€” Aggregation Only

// 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' },
});

Writing Data β€” BulkWrite Only

// 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 } },
]);

Connection Pool Presets

PresetMax PoolMin PoolUse Case
high202APIs, high-traffic services
standard102Default for most services
low51Background workers, cron jobs

Built-in Sanitization and Guardrails

All query inputs are automatically sanitized. The sanitizer uses an allowlist of known-safe query operators β€” standard operators pass through while dangerous ones are stripped.

CategoryOperatorsWhat happens
Safe (allowed) $gte, $lt, $in, $nin, $ne, $eq, $regex, $exists, $and, $or, $not, $nor, $elemMatch, $all, $size, $type, $expr, $text, geo, bitwise Key allowed through, value recursively sanitized
Dangerous (stripped) $where, $function, $accumulator Stripped automatically β€” these execute arbitrary JavaScript
Unknown (stripped) Any unrecognized $ key Stripped as defense in depth

This means standard queries just work without any special options:

// All of these work by default β€” no special options needed:
const entries = await queryMany('logs', [
  { $match: { timestamp: { $gte: new Date(since) } } },
]);

const total = await count('waf_events', { event_at: { $gte: sinceDate } });

const latest = await queryOne('events', {
  level: { $in: ['error', 'fatal'] },
  timestamp: { $gte: cutoff },
});

// Dangerous operators are automatically stripped:
// { $where: 'this.isAdmin' }     β†’ stripped (JS execution)
// { $function: { body: '...' } } β†’ stripped (JS execution)

Disable sanitization entirely with sanitize: false in StrictDB.create() config or sanitize = false in claude-mastery-project.conf.

{ trusted: true } β€” Escape Hatch

If you need an operator not in the allowlist, queryOne(), queryMany(), and count() accept { trusted: true } to skip sanitization entirely. This should be rare β€” if you use it frequently, add the operator to the SAFE_OPERATORS configuration in StrictDB instead.

// Only needed for operators NOT in the allowlist:
const results = await queryMany('collection', pipeline, { trusted: true });
const total = await count('collection', match, { trusted: true });
const one = await queryOne('collection', match, { trusted: true });

When to use { trusted: true }

  • Non-standard operators not in the allowlist
  • You validated/sanitized input yourself at a higher layer

When NOT to use it

  • Standard operators ($gte, $in, $regex, etc.) β€” these work by default
  • Raw user input flows directly into $match without validation

Additional Features

  • Singleton per URI β€” same STRICTDB_URI always returns the same client, prevents pool exhaustion
  • Next.js hot-reload safe β€” persists connections via globalThis during development
  • Transaction support β€” withTransaction() for multi-document atomic operations
  • Change Stream access β€” rawCollection() for real-time event processing
  • Graceful shutdown β€” gracefulShutdown() closes all pools on SIGTERM, SIGINT, uncaughtException, and unhandledRejection β€” 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

Test Query Master β€” scripts/db-query.ts

One of the biggest problems with AI-assisted database development: Claude scatters random query scripts all over your project. The Test Query Master solves this completely.

The Problem

Without guardrails, Claude creates ad-hoc database scripts everywhere β€” scripts/check-users.ts, src/utils/debug-query.ts, temp-lookup.js β€” making it impossible to tell test code from production code.

The Solution

Every dev/test query gets its own file in scripts/queries/ and is registered in the master index. Production code in src/ stays clean. One command shows everything: npx tsx scripts/db-query.ts --list

scripts/queries/find-expired-sessions.ts
import { queryMany } from 'strictdb';

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`);
  },
};

Then register in scripts/db-query.ts and run: npx tsx scripts/db-query.ts find-expired-sessions

Every query uses StrictDB β€” same connection pool, same patterns, same rules. When you're done exploring, just delete the file and its registry entry.

Content Builder β€” scripts/build-content.ts

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 with one command.

scripts/content.config.json (article registry)
{
  "articles": [
    {
      "id": "getting-started",
      "published": true,
      "mdSource": "content/getting-started.md",
      "htmlOutput": "public/articles/getting-started/index.html",
      "title": "Getting Started Guide",
      "description": "Everything you need to know.",
      "url": "https://example.com/articles/getting-started/",
      "datePublished": "2026-01-15",
      "category": "Guides",
      "keywords": ["setup", "installation"]
    }
  ]
}

Each generated page includes: Open Graph, Twitter Cards, Schema.org JSON-LD, syntax highlighting, optional sidebar TOC, and parent/child article relationships.

npm scripts
pnpm content:build              # Build all published articles
pnpm content:build:id my-post   # Build a single article
pnpm content:list               # List all articles and status
pnpm content:dry-run            # Preview what would build

All Scripts β€” package.json

Everything is tied together through package.json scripts. No random npx commands to remember.

CommandWhat it does
Development
pnpm devDev server with hot reload
pnpm dev:websiteDev server on port 3000
pnpm dev:apiDev server on port 3001
pnpm dev:dashboardDev server on port 3002
pnpm buildType-check + compile TypeScript
pnpm startRun production build
pnpm typecheckTypeScript check only (no emit)
pnpm lintSame as typecheck
Testing
pnpm testRun ALL tests (unit + E2E)
pnpm test:unitUnit/integration tests (Vitest)
pnpm test:unit:watchUnit tests in watch mode
pnpm test:coverageUnit tests with coverage report
pnpm test:e2eE2E tests (kills ports β†’ spawns servers β†’ Playwright)
pnpm test:e2e:headedE2E with visible browser
pnpm test:e2e:uiE2E with Playwright UI mode
pnpm test:e2e:chromiumE2E on Chromium only (fast)
pnpm test:e2e:reportOpen last Playwright HTML report
pnpm test:kill-portsKill processes on test ports (4000, 4010, 4020)
Test Servers
pnpm dev:test:websiteTest server on port 4000
pnpm dev:test:apiTest server on port 4010
pnpm dev:test:dashboardTest server on port 4020
Database
pnpm db:query <name>Run a dev/test database query
pnpm db:query:listList all registered queries
Content
pnpm content:buildBuild all published MD β†’ HTML
pnpm content:build:id <id>Build a single article by ID
pnpm content:listList all articles
pnpm content:dry-runPreview what would build
Monitoring & Docker
pnpm ai:monitorFree monitor mode β€” live AI activity (run in separate terminal, no API key needed)
pnpm docker:optimizeAudit Dockerfile (use /optimize-docker in Claude)
Utility
pnpm cleanRemove dist/, coverage/, test-results/

Documentation Templates

Pre-structured docs that Claude actually follows. Each template uses the β€œSTOP” pattern β€” explicit boundaries that prevent Claude from making unauthorized changes.

ARCHITECTURE.md

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
  • β€œ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 StrictDB.
- Skip TypeScript for a quick fix β†’ STOP. TypeScript is non-negotiable.
- Deploy without tests β†’ STOP. Write tests first.

DECISIONS.md

project-docs/DECISIONS.md

Architectural Decision Records (ADRs) that document why you chose X over Y. Includes a template and two starter decisions:

  • ADR-001: TypeScript Over JavaScript β€” AI needs explicit type contracts to avoid guessing
  • ADR-002: StrictDB as Unified Database Driver β€” prevents connection pool exhaustion

Each ADR has: Context, Decision, Alternatives Considered (with pros/cons table), and Consequences.

INFRASTRUCTURE.md

project-docs/INFRASTRUCTURE.md

Deployment and environment details:

  • Environment overview diagram (production vs local)
  • Environment variables table (required, where, purpose)
  • Deployment prerequisites and steps
  • Rollback procedures
  • Monitoring setup

Testing Methodology

From the V5 testing methodology β€” a structured approach to testing that prevents the most common AI-assisted testing failures.

CHECKLIST.md

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 (βœ… passed, ❌ failed, ⬜ not tested) for every feature area.

ISSUES_FOUND.md

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.

Test Structure Pattern

Every test in this project follows the Arrange β†’ Act β†’ Assert pattern:

describe('[Feature]', () => {
  describe('[Scenario]', () => {
    it('should [expected behavior] when [condition]', async () => {
      // Arrange β€” set up test data
      // Act β€” perform the action
      // Assert β€” verify SPECIFIC outcomes
    });
  });
});

E2E Test Requirements

Every E2E test (Playwright) must verify four things:

  1. Correct URL after navigation
  2. Key visible elements are present
  3. Correct data is displayed
  4. Error states show proper messages

E2E Infrastructure β€” playwright.config.ts

The Playwright config is pre-wired with test ports, automatic server spawning, and port cleanup. You never have to manually start servers for E2E tests.

How It Works

  1. pnpm test:e2e β€” kills anything on test ports (4000, 4010, 4020)
  2. Playwright spawns servers via webServer config on test ports
  3. Tests run against the test servers
  4. Servers shut down automatically when tests complete

When Is a Test Done?

  • βœ“ At least one toHaveURL() assertion
  • βœ“ At least one toBeVisible() assertion
  • βœ“ At least one toContainText() data assertion
  • βœ“ Error case covered
  • βœ“ No // TODO placeholders
Test commands
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 report

/create-e2e Slash Command

Use /create-e2e <feature-name> to generate a properly structured E2E test. Claude will:

  1. Read the source code for the feature being tested
  2. Identify all URLs, elements, and data to verify
  3. Ask what specific success criteria you expect (if not obvious)
  4. Create the test at tests/e2e/[name].spec.ts with happy path, error cases, and edge cases
  5. Verify the test meets the β€œdone” checklist before finishing

Windows Users β€” VS Code in WSL Mode

If you're developing on Windows, this is the single biggest performance improvement you can make β€” and most people don't even know it exists.

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. Everything just works β€” but 5-10x faster.

Without WSL Mode

  • HMR takes 2-5 seconds per change
  • Playwright tests are slow and flaky
  • File watching misses changes or double-fires
  • Node.js filesystem ops hit NTFS translation layer
  • git status takes seconds on large repos

With WSL Mode

  • HMR is near-instant (<200ms)
  • Playwright tests run at native Linux speed
  • File watching is reliable and fast
  • Native ext4 filesystem β€” no translation
  • git status is instant

Setup (One Time)

# 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 automatically

The Critical Mistake

Your 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 β€” every file operation still crosses the slow Windows/Linux boundary.

# 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-app

Run /setup in Claude Code to auto-detect your environment and get specific instructions if something is misconfigured.

Global CLAUDE.md β€” Security Gatekeeper

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 .env files. NEVER auto-deploy. NEVER hardcode credentials. NEVER rename without a plan. These rules 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, StrictDB pattern β€” all enforced across every project.

Global Permission Denials

The companion settings.json explicitly denies Claude access to .env, .env.local, secrets.json, id_rsa, and credentials.json at the permission level β€” before hooks even run.

Coding Standards

Patterns and practices enforced across the project through CLAUDE.md rules, hooks, and code review.

Imports

// 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';

Error Handling

// 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
}

Naming Safety

Renaming packages, modules, or key variables mid-project causes cascading failures. If you must rename:

  1. Create a checklist of ALL files and references first
  2. Use IDE semantic rename (not search-and-replace)
  3. Full project search for old name after renaming
  4. Check: .md, .txt, .env, comments, strings, paths
  5. Start a FRESH Claude session after renaming

Plan Mode β€” Named Steps + Replace, Don't Append

Every plan step MUST have a unique, descriptive name so you can reference it unambiguously:

Step 1 (Project Setup): Initialize repo with TypeScript
Step 2 (Database Layer): Configure StrictDB
Step 3 (Auth System): Implement JWT authentication

When modifying a plan, Claude tends to append instead of replacing β€” creating contradictions. The rules:

  • 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

Monitor Your Rules

Full disclosure: RuleCatch.AI is built by TheDecipherist β€” the same developer behind this starter kit. It's purpose-built for catching the exact issues AI-assisted development introduces.

Try It Now β€” Free Monitor Mode

See what your AI is doing in real-time. No API key, no account, no setup β€” just open a separate terminal and run:

# Open a separate terminal and run this while Claude works
npx @rulecatch/ai-pooler monitor --no-api-key

Also available as pnpm ai:monitor. You'll instantly see every tool call, token count, cost per turn, and which files Claude is touching β€” all updating live. Zero token overhead. This is the free preview that lets you see what you've been missing.

Unlock the Full Experience

Why you'd want it: AI models break your CLAUDE.md rules more often than you'd expect β€” wrong language, skipped patterns, hardcoded values, ignored constraints. Code that looks right and passes linting, but violates your project's actual standards. RuleCatch.AI bridges the gap between detecting these violations and fixing them.

AI-Pooler (Free Monitor Mode)

Free monitor mode works instantly β€” no API key needed. See every tool call, token, cost, and file access in a live terminal view. With an API key: adds persistent violation tracking, session history, and cost analytics

Dashboard

Violations across 18 rule categories, session analytics (tokens, cost, lines/hour), trend reports, per-file attribution. Alerts via Slack, Discord, PagerDuty, and more

MCP Server

Gives Claude direct read access to violation data. Ask: "Show all security violations this week" or "Create a plan to fix today's violations" β€” Claude reviews, analyzes, and generates file-by-file fix plans without leaving your session

200+ Rules & Privacy-First

Security, TypeScript, React, Next.js, MongoDB, Docker β€” violations in under 100ms. AES-256-GCM client-side encryption. You hold the key. US and EU data isolation, fully GDPR compliant

RuleCatch.AI Dashboard β€” violation analytics, daily trends, category breakdown, and top triggered rules

The RuleCatch dashboard β€” violation trends, category breakdown, per-file attribution, and top triggered rules at a glance. Configure alerts via Slack, Discord, PagerDuty, and more.

Full Setup (with API Key)

# Install the AI-Pooler with your API key (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 init
RuleCatch AI-Pooler Monitor β€” real-time session tracking showing tokens, cost, violations, and tool usage

The AI-Pooler free monitor in action β€” tokens, cost, and tool usage updating in real time. Try it now: open a separate terminal and run npx @rulecatch/ai-pooler monitor --no-api-key

Explore RuleCatch.AI 7-day free trial - no credit card required

Recommended MCP Servers

MCP (Model Context Protocol) servers extend Claude's capabilities by giving it tools beyond reading and writing files. Each server below solves a specific problem in AI-assisted development. All are optional β€” install the ones that fit your workflow.

Context7 β€” Live Documentation

Claude's training data has a knowledge cutoff. When it generates code for a library, it might use APIs that have been renamed, deprecated, or don't exist in your version. Context7 fetches up-to-date, version-specific documentation and code examples directly from official sources and injects them into Claude's context.

What it solves: Hallucinated APIs, outdated code patterns, version mismatches

How to use: Add use context7 to your prompt β€” Context7 automatically identifies the relevant library and fetches current docs

claude mcp add context7 -- npx -y @upstash/context7-mcp@latest

npm: @upstash/context7-mcp Β· GitHub

GitHub MCP β€” Repository Management

Gives Claude direct access to the GitHub API β€” create and review PRs, manage issues, trigger CI/CD workflows, search code across repos, and handle branch operations. Instead of switching between Claude and the GitHub UI, Claude can do it all in-session.

What it solves: Context-switching between Claude and GitHub for PR reviews, issue management, and CI/CD

Toolsets: Repository management, issues, pull requests, actions, code security, discussions, notifications

claude mcp add github -- npx -y @modelcontextprotocol/server-github

Note: GitHub has also released an official GitHub MCP Server with expanded toolsets.

npm: @modelcontextprotocol/server-github Β· GitHub (official)

Playwright MCP β€” Browser Automation

Gives Claude the ability to interact with web pages through structured accessibility snapshots β€” no vision models or screenshots needed. Claude can navigate pages, click elements, fill forms, and verify content using the page's accessibility tree.

What it solves: E2E test debugging, verifying UI behavior, interacting with web apps during development

How it works: Uses Playwright's accessibility tree (not screenshots) β€” fast, lightweight, and LLM-friendly. Supports Chrome, Firefox, WebKit, and 143+ device emulation profiles

claude mcp add playwright -- npx -y @playwright/mcp@latest

npm: @playwright/mcp Β· GitHub

ClassMCP β€” Semantic CSS for AI

By TheDecipherist β€” open source (MIT license)

MCP server that provides semantic CSS class patterns to Claude, reducing token usage when working with styles. Instead of Claude guessing class names or hallucinating utility classes, ClassMCP feeds it the correct patterns from your project's CSS framework. Auto-included in all CSS-enabled profiles.

What it solves: Hallucinated CSS class names, inconsistent styling patterns, wasted tokens on style guessing

claude mcp add classmcp -- npx -y classmcp@latest

npm: classmcp Β· Website

StrictDB-MCP β€” Database Context for AI

By TheDecipherist β€” open source (MIT license)

MCP server that gives Claude direct access to StrictDB schema discovery, query validation, and explain plans. Claude can inspect collection schemas, dry-run queries before execution, and understand your database structure without you pasting it into context. Auto-included in all database-enabled profiles.

What it solves: Hallucinated collection names, wrong field types, queries that fail on execution, missing context about database schema

claude mcp add strictdb-mcp -- npx -y strictdb-mcp@latest

npm: strictdb-mcp

RuleCatch MCP β€” AI Session Analytics

Already covered in detail in the Monitor Your Rules section above. Gives Claude direct read access to violation data so it can query what rules it's breaking and generate fix plans.

npx @rulecatch/mcp-server init

npm: @rulecatch/mcp-server Β· RuleCatch.AI

See the Claude Code Mastery Guide for the complete MCP server directory.

Credits

The Complete Guide to Claude Code by TheDecipherist

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