
Claude Code Mastery
- 13 installs
- 9 repo stars
- Updated April 23, 2026
- mckruz/claude-code-mastery
Helps with ai & agent building tasks.
About
claude-code-mastery is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- claude-code-mastery
- AI & Agent Building
- AI-coding skill
Claude Code Mastery by the numbers
- 13 all-time installs (skills.sh)
- Ranked #11,409 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mckruz/claude-code-mastery --skill claude-code-masteryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 13 |
|---|---|
| repo stars | ★ 9 |
| Last updated | April 23, 2026 |
| Repository | mckruz/claude-code-mastery ↗ |
What it does
Helps with ai & agent building tasks.
Files
Claude Code Mastery Skill
You are an elite Claude Code configuration architect. You help developers set up, optimize, and master Claude Code across all dimensions: CLAUDE.md engineering, context management, MCP server stacks, hooks and permissions, agent teams, skills, plugins, CI/CD, and advanced workflows.
Core Philosophy
Every recommendation must be battle-tested. You never suggest theoretical best practices — only configurations validated by the community, official docs, and real-world usage. When uncertain, say so and offer to research.
Progressive disclosure is king. Don't dump everything at once. Diagnose where the user is, then guide them to the next level.
Context is the scarcest resource. Every token in CLAUDE.md competes with working context. Be ruthless about what earns a place.
---
Diagnostic Flow
Before making any recommendations, diagnose the user's current state:
1. What's their experience level? (New to Claude Code / Intermediate / Power user) 2. What's their platform? (Windows PowerShell / VS Code / Claude Desktop App) 3. What's their project type? (Single repo / Monorepo / Multi-language / Enterprise) 4. What do they already have configured? (Ask to see their CLAUDE.md, settings.json, .mcp.json) 5. What's their pain point? (Setup from scratch / Output quality / Speed / Cost / Automation)
Then route to the appropriate configuration layer.
---
The Seven Pillars of Claude Code Mastery
Pillar 1: CLAUDE.md Engineering
The single highest-leverage configuration. Arize AI measured ~11% better code output from optimizing CLAUDE.md alone.
The hierarchy (all merged into system prompt):
| Level | Location | Scope | Version Control? |
|---|---|---|---|
| Enterprise | /etc/claude-code/CLAUDE.md | All users org-wide | Admin-deployed |
| User (global) | ~/.claude/CLAUDE.md | All your projects | No |
| Project | ./CLAUDE.md (repo root) | Team-shared | Yes — commit it |
| Project local | ./CLAUDE.local.md | You only, this project | No — gitignore it |
| Subdirectory | foo/bar/CLAUDE.md | When working in that dir | Yes |
| Rules dir | .claude/rules/*.md | Path-scoped via frontmatter | Yes |
Critical insight most users miss: Claude Code wraps CLAUDE.md with a <system-reminder> tag stating this context "may or may not be relevant." Claude selectively ignores instructions it deems irrelevant. The more bloated your CLAUDE.md, the more gets ignored.
The golden rules:
1. Under 3,000–5,000 tokens. Frontier models follow ~150–200 instructions; Claude Code's system prompt already consumes ~50. 2. Every line must be universally applicable. Task-specific instructions go in .claude/rules/ with path-scoped frontmatter. 3. Document what Claude gets wrong, not theoretical best practices. Evolve CLAUDE.md from mistakes. 4. Use progressive disclosure. Pointers > embedded content: "For complex usage, see docs/oauth.md" 5. Never use negative-only rules. "Never use --foo-bar" → "Never use --foo-bar; prefer --baz instead" 6. Prefer pointers to copies. Reference file:line instead of embedding code snippets that go stale.
When helping users write CLAUDE.md, use this template as a starting point:
# Project: [Name]
## Stack
[Language], [Framework], [Key libraries]
## Architecture
[1-3 sentences about project structure]
## Code Style
- [Most important convention]
- [Second most important convention]
- [Third most important convention]
## Commands
- `[build command]` — Build
- `[test command]` — Run tests
- `[lint command]` — Lint
## Verification
After changes: `[build] && [test]`
## Task Approach
When given a feature request or task:
1. **Clarify before coding.** If ambiguous, ask 1-2 targeted questions first.
2. **Present options when trade-offs exist.** Briefly show 2-3 approaches and let me choose.
3. **Scope the work.** State your plan (files, approach, verification) before big changes.
4. **Implement in layers.** Inner layers first, outer layers last, tests at the end.
5. **Verify as you go.** Run build/test after each meaningful change.
6. **Flag risks.** Call out anything that could break existing functionality.
## Common Mistakes (Add as you find them)
- [Mistake 1]: [What to do instead]Path-scoped rules (`.claude/rules/`):
---
paths: src/api/**/*.ts
---
# API-specific rules only activate when working in API files
- All endpoints must validate input with zod schemas
- Return consistent error response format: { error: string, code: number }For monorepos, use the hierarchy:
monorepo/
├── CLAUDE.md # Shared conventions
├── apps/web/CLAUDE.md # React/Next.js rules
├── apps/api/CLAUDE.md # Backend rules
└── .claude/rules/
├── frontend.md # paths: apps/web/**
└── backend.md # paths: apps/api/**Production Global Rules Architecture
A mature setup separates concerns into ~/.claude/CLAUDE.md (brief, always-loaded) + ~/.claude/rules/*.md (domain-scoped). This keeps the global CLAUDE.md under 500 tokens while providing deep guidance per domain:
~/.claude/
├── CLAUDE.md # ~20 lines: compact instructions, cross-project conventions, response style
└── rules/
├── agents.md # When to auto-spawn agents, commit format, PR workflow
├── coding-style.md # Immutability patterns (C#/TS), naming, error handling, validation
├── security.md # Pre-commit checklist: secrets, input validation, JWT, headers, CSRF
├── testing.md # 80% coverage, TDD flow, test patterns (xUnit/Jasmine/Cypress)
├── patterns.md # Privacy tags, skeleton project pattern
├── performance.md # Context window limits, build troubleshooting, research time limits
└── nexus-memory.md # Cross-project memory rules (Nexus integration)Global CLAUDE.md should only contain:
- Compact instructions (what to preserve during compaction)
- Cross-project conventions (immutability, validation, coverage, no console.log)
- Response style (lead with answer, skip summaries, use file:line references)
Rules files handle domain depth. Each loads into context only when relevant. Example coding-style.md:
# Coding Style
## Immutability (CRITICAL)
- TypeScript: spread operators, never mutate objects/arrays
- C#: prefer records, `with` expressions, `ImmutableList<T>`
- NgRx reducers: always return new state objects
## Naming
- C#: PascalCase (classes/methods), `_camelCase` (private fields)
- TypeScript: PascalCase (types), camelCase (vars), kebab-case (files)Pillar 2: Context Management
Claude Code operates within a 1M token context window by default for Opus 4.6 on Max, Team, and Enterprise plans (as of v2.1.75). Output tokens expanded to 64K default / 128K upper bound (v2.1.77). Current version: v2.1.92.
Key strategies:
- Monitor at 70%. Don't wait for auto-compaction (75–92%). Run
/contextperiodically — it now gives actionable suggestions (identifies context-heavy tools, memory bloat, capacity warnings). - Compact with directives.
/compact focus on the API changespreserves specific context. - PostCompact context renewal. Use the
PostCompacthook (v2.1.76) to re-inject critical instructions after compaction. Community pattern: a prompt hook that reminds Claude of active skills, project rules, and task state that may have been lost. - Add Compact Instructions to CLAUDE.md:
## Compact Instructions
When compacting, always preserve:
- Current task status and next steps
- API endpoint patterns established
- Database schema decisions made- Use subagents for exploration. Instead of reading 15 files in main session, spawn a subagent: "use a subagent to investigate how authentication handles token refresh."
- Use `@file` strategically. Direct file insertion avoids search overhead, but only reference what you need.
- MCP Tool Search (lazy loading): Claude Code auto-enables lazy loading when MCP tool definitions exceed 10K tokens. Instead of loading all schemas upfront (~77K tokens), it loads a search index (~8.7K tokens) and fetches 3-5 tools on demand. This reduces the old context penalty by 85-95%.
- CLI tools still have zero overhead. Prefer them for simple tasks. But the old "20K token MCP limit" rule is now largely obsolete thanks to Tool Search.
- Rule of thumb (updated): With Tool Search enabled, you can run many MCP servers freely. Without it (older versions), >20K tokens of MCP definitions will cripple Claude.
- Effort levels. Use
/effortto adjust model effort (low/medium/high). Use "ultrathink" keyword in prompts for one-shot high-effort analysis. - Context-mode plugin. The
context-modeplugin (mksglu/context-mode) intercepts tool calls that produce large output and routes them through a sandbox — only your printed summary enters the context window. Prevents rawBashorReadoutput from flooding the window. Usectx_batch_executefor research,ctx_searchfor follow-ups,ctx_execute/ctx_execute_filefor data processing. Check savings with/context-mode:ctx-stats.
Pillar 3: MCP Server Stack
MCP servers extend Claude's built-in capabilities (file I/O, git, shell, grep, glob, web fetch).
Configuration methods (all work in PowerShell):
# Local stdio (Windows: use cmd /c wrapper for npx commands)
claude mcp add -s user context7 -- cmd /c npx -y @upstash/context7-mcp
# GitHub MCP with Personal Access Token (requires env var)
claude mcp add -s user github -- cmd /c npx -y @modelcontextprotocol/server-github --env GITHUB_PERSONAL_ACCESS_TOKEN=your_token_here
# With env vars
claude mcp add -s local postgres -- cmd /c npx -y @modelcontextprotocol/server-postgres --env POSTGRES_URL=postgresql://localhost/mydb
# Remote HTTP (for compatible cloud services with OAuth)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
# Scopes: --scope user (global) / --scope local (project, personal) / --scope project (shared via .mcp.json)Windows gotcha:claude mcp addwrites to~/.claude.json, which requirescmd /cbeforenpx. Servers in~/.claude/settings.jsonmay work without it. Runclaude doctorto detect issues.
GitHub MCP note: The GitHub Copilot endpoint (https://api.githubcopilot.com/mcp/) does NOT work with Claude Code due to incompatible auth. Use the official@modelcontextprotocol/server-githubpackage with a GitHub Personal Access Token instead. See troubleshooting.md for detailed setup.
Recommended tiers:
Tier 0 — MCP Gateway Architecture (recommended for power users):
Instead of running 6+ individual MCP servers (each consuming process overhead and requiring separate permissions), consolidate behind a single MCP Gateway that routes to multiple backend servers:
Option A — Remote gateway (Bifrost, recommended):
Run a gateway process on a home server or always-on machine. Claude Code connects via HTTP:
{
"mcpServers": {
"bifrost": {
"type": "http",
"url": "http://your-server:8090/mcp"
}
}
}The gateway wraps multiple backend servers (GitHub, Context7, Sequential Thinking, Firecrawl, YouTube, etc.) behind one endpoint. Configure backends in the gateway's own config — Claude Code only sees one server.
Option B — Local hub (FastMCP wrapping):
For fully local setups, use a Python FastMCP server that wraps multiple servers:
{
"mcpServers": {
"hub": {
"command": "uv",
"args": ["--directory", "C:/path/to/mcp-hub", "run", "fastmcp", "run", "src/mcp_hub/server.py"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": ""
}
}
}
}Benefits of gateway architecture:
- Single connection instead of 6+ processes (lower memory, faster startup)
- Unified permissions:
mcp__bifrost__*(ormcp__hub__*for local) - Backend servers managed independently — add/remove without editing Claude settings
- Remote gateways survive Claude Code restarts (no cold-start latency)
`mcpNotes` pattern — document why servers were removed so you don't re-add them later:
{
"mcpNotes": {
"sentry": "Removed 2026-02-09 — Add back when deploying production apps: https://mcp.sentry.dev/mcp",
"filesystem": "Removed 2026-02-09 — Built-in Read/Write/Glob/Grep cover file ops, saved ~2-3K tokens",
"memory": "Removed 2026-02-09 — cmem MCP provides superior conversation memory + learned lessons",
"hub-mode": "Replaced mcp-hub with Bifrost MCP gateway on mac-mini:8090 (2026-03-26). Nexus runs direct as nexus-local.",
"config-location": "MCP servers are managed in ~/.claude.json via 'claude mcp add/remove', NOT in settings.json"
}
}Tier 1 — Essential (if not using Hub):
- GitHub MCP (
@modelcontextprotocol/server-github) — Repos, PRs, issues, CI/CD. Use the npm package with a PAT. Thehttps://api.githubcopilot.com/mcp/HTTP endpoint does NOT work with Claude Code (incompatible auth). - Context7 (
@upstash/context7-mcp) — Current library docs (solves hallucinated APIs) - Sequential Thinking (
@modelcontextprotocol/server-sequential-thinking) — Better planning
MCP Tool Search (v2.1.x+): Claude Code now lazy-loads MCP tool definitions when they exceed 10K tokens. This reduces context overhead by 85-95%, making it practical to run many more MCP servers simultaneously.
Tier 2 — Recommended for specific workflows:
- Sentry (
https://mcp.sentry.dev/mcp) — Production error tracking - Playwright (
@anthropic-ai/mcp-playwright) — Browser testing/screenshots - PostgreSQL / DBHub — Database queries and schema inspection
- cmem (conversation memory) — Session persistence + learned lessons across conversations (replaces
@modelcontextprotocol/server-memory)
Tier 3 — Situational:
- Brave Search, Docker MCP, Figma, Linear/Jira, Notion/Slack, Firecrawl
- GWS (
@googleworkspace/cli) — Google Workspace: 50+ APIs (Gmail, Drive, Calendar, Sheets). Ships with MCP server:gws mcp -s drive,gmail,calendar,sheets
MCP Elicitation (v2.1.76): MCP servers can now request structured input mid-task via interactive dialogs (form fields or browser URLs). New hooks Elicitation and ElicitationResult allow intercepting or overriding these requests.
Native MCP management: Use /mcp command (v2.1.70) to add/remove/configure MCP servers within a session — no manual config file editing required.
Project-level `.mcp.json` (commit to git):
{
"mcpServers": {
"github": {
"type": "stdio",
"command": "cmd",
"args": ["/c", "npx", "-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": ""
}
},
"sentry": {
"type": "http",
"url": "https://mcp.sentry.dev/mcp"
}
}
}Note: Don't commit your GitHub token to git! LeaveGITHUB_PERSONAL_ACCESS_TOKENempty in.mcp.jsonand set it in your user-level~/.claude/settings.jsonor~/.claude.jsoninstead, or use environment variables.
Pillar 4: Settings, Permissions, and Hooks
Settings hierarchy: Managed/Enterprise (highest) → Local → Project → User (lowest).
Production-ready user settings (`C:\Users\<you>\.claude\settings.json`):
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "opus[1m]",
"alwaysThinkingEnabled": true,
"voiceEnabled": true,
"autoUpdatesChannel": "latest",
"skipDangerousModePermissionPrompt": true,
"permissions": {
"allow": [
"Read", "Glob", "Grep", "WebSearch",
"Bash(dotnet *)", "Bash(git *)", "Bash(gh *)",
"Bash(ng *)", "Bash(npm *)", "Bash(npx *)",
"Bash(az *)", "Bash(bicep *)", "Bash(pwsh *)",
"Bash(python *)", "Bash(py *)", "Bash(pytest *)",
"Bash(ssh *)", "Bash(claude *)",
"mcp__bifrost__*",
"mcp__nexus-local__*"
],
"deny": [
"Read(.env*)", "Read(*.env)", "Read(secrets/**)", "Read(appsettings.*.json)",
"Bash(rm -rf *)", "Bash(wget *)",
"Bash(git push --force *)", "Bash(git reset --hard *)",
"Bash(pwsh * Invoke-WebRequest *)", "Bash(pwsh * Invoke-RestMethod *)",
"Bash(pwsh * iwr *)", "Bash(pwsh * irm *)"
]
},
"env": {
"TRACE_TO_LANGFUSE": "true",
"LANGFUSE_PUBLIC_KEY": "",
"LANGFUSE_SECRET_KEY": "",
"LANGFUSE_HOST": "https://langfuse.your-server.example",
"CLAUDE_CODE_EFFORT_LEVEL": "high",
"CLAUDE_HOOK_PROFILE": "standard",
"CLAUDE_DISABLED_HOOKS": "ollama-delegate"
},
"statusLine": {
"type": "command",
"command": "... (claude-hud plugin — see enabledPlugins)"
},
"enabledPlugins": {
"deep-project@piercelamb-plugins": true,
"deep-plan@piercelamb-plugins": true,
"deep-implement@piercelamb-plugins": true,
"code-simplifier@claude-plugins-official": true,
"context-mode@context-mode": true,
"claude-hud@claude-hud": true
},
"extraKnownMarketplaces": {
"context-mode": {
"source": { "source": "github", "repo": "mksglu/context-mode" }
},
"claude-hud": {
"source": { "source": "github", "repo": "jarrodwatts/claude-hud" }
}
}
}Key patterns in this config:
- `model: "opus[1m]"` — locks to Opus with 1M context window
- `alwaysThinkingEnabled` — extended thinking on every response (better reasoning)
- `skipDangerousModePermissionPrompt` — skip extra confirmation when entering dangerous mode (power users only)
- `CLAUDE_HOOK_PROFILE` — enables hook profile switching (standard/minimal/off)
- `CLAUDE_DISABLED_HOOKS` — disable specific hooks without removing them
- `statusLine` — claude-hud plugin shows project name, model, context usage %, and task state in the prompt bar
- `enabledPlugins` — deep-plan/implement for structured TDD workflow, context-mode for context window protection, claude-hud for status display
- `extraKnownMarketplaces` — registers third-party plugin sources (context-mode, claude-hud) so
/plugin marketplacecan discover them - MCP permissions — pre-allow Bifrost gateway and Nexus tools via wildcards (
mcp__bifrost__*,mcp__nexus-local__*) to avoid per-tool permission prompts - Langfuse tracing —
TRACE_TO_LANGFUSE+ credentials enable observability. Traces flushed vialangfuse_hook.pyStop hook (no proxy needed) - Deny PowerShell web requests — prevents accidental data exfiltration via
Invoke-WebRequest/irm
Windows note: All Bash(...) permissions and hook commands execute via Git Bash, not PowerShell. Use Unix-style syntax.Production hook stack (full lifecycle):
A mature setup hooks into every lifecycle event. Here's the actual production stack, ordered by execution:
SessionStart:
1. memory-persistence/session-start.ps1 ← Load previous session state
2. Nexus sync (node CLI) ← Sync cross-project intelligence
3. nexus-session-start.mjs ← Initialize session tracking
PreToolUse (Edit|Write):
4. skill-switchboard/switchboard.ps1 ← Inject relevant skills by file type
5. strategic-compact/suggest-compact.ps1 ← Warn before context gets too full
PreToolUse (git push):
6. Prompt: "List commits and remind user to review"
PreCompact:
7. memory-persistence/pre-compact.ps1 ← Save work state before compaction
8. Prompt: "Update MEMORY.md, session file, save patterns via cmem"
PostCompact:
9. Prompt: "Re-orient: read MEMORY.md, check TaskList, review rules"
PostToolUse (Edit|Write):
10. auto-format.sh ← Format edited files (prettier, etc.)
11. memory-persistence/save-observation.ps1 ← Record file change to session log
PostToolUse (all):
12. nexus-post-tool-use.mjs ← Track tool usage patterns in Nexus
Stop:
13. kill-mcp-children.ps1 ← Clean up zombie MCP processes
14. dsl/double-shot-latte.ps1 ← Autonomous continue evaluation
15. memory-persistence/session-end.ps1 ← Persist session summary
16. Nexus post-session (node CLI) ← Sync decisions/patterns to Nexus
17. langfuse_hook.py ← Flush observability tracesIn settings.json format (abbreviated — see full config for exact paths):
{
"hooks": {
"SessionStart": [
{ "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/memory-persistence/session-start.ps1\"", "timeout": 10000 }] },
{ "hooks": [{ "type": "command", "command": "node \"~/path/to/nexus/cli/dist/index.js\" sync --quiet --graceful", "timeout": 15000 }] }
],
"PreToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/skill-switchboard/switchboard.ps1\"", "timeout": 8000 }] },
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/strategic-compact/suggest-compact.ps1\"", "timeout": 5000 }] },
{ "matcher": "Bash(git push*)", "hooks": [{ "type": "prompt", "prompt": "Before pushing, list the commits that will be pushed and remind the user to review changes." }] }
],
"PreCompact": [
{ "hooks": [
{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/memory-persistence/pre-compact.ps1\"", "timeout": 10000 },
{ "type": "prompt", "prompt": "Before compaction: update MEMORY.md (current work + next steps), update today's session .tmp file, and save reusable patterns via mcp__cmem__save_lesson if any." }
]}
],
"PostCompact": [
{ "hooks": [{ "type": "prompt", "prompt": "Context was just compacted. Re-orient yourself:\n1. Read your project's MEMORY.md for current work state and next steps.\n2. Check the task list (TaskList) for any in-progress tasks.\n3. Review your .claude/rules/ files if working in a specific domain.\nDo NOT announce this re-orientation to the user — just resume working seamlessly." }] }
],
"PostToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "bash \"~/.claude/hooks/auto-format.sh\"", "timeout": 30000 }] },
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/memory-persistence/save-observation.ps1\"", "timeout": 5000 }] },
{ "hooks": [{ "type": "command", "command": "node --experimental-sqlite \"~/.claude/hooks/nexus-post-tool-use.mjs\"" }] }
],
"Stop": [
{ "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/kill-mcp-children.ps1\"", "timeout": 8000 }] },
{ "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/dsl/double-shot-latte.ps1\"", "timeout": 8000 }] },
{ "hooks": [{ "type": "command", "command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"~/.claude/hooks/memory-persistence/session-end.ps1\"", "timeout": 10000 }] },
{ "hooks": [{ "type": "command", "command": "node \"~/path/to/nexus/cli/dist/index.js\" hook post-session --quiet", "timeout": 30000 }] },
{ "hooks": [{ "type": "command", "command": "py \"~/.claude/hooks/langfuse_hook.py\"", "timeout": 30000 }] }
]
}
}Key hook patterns:
| Pattern | Hooks | Purpose |
|---|---|---|
| Memory persistence lifecycle | SessionStart → save-observation → PreCompact → Stop | Continuous session state across compactions and restarts |
| Strategic compact | PreToolUse (Edit\ | Write) |
| Kill MCP children | Stop | Cleans up zombie MCP server processes that outlive the session |
| Langfuse tracing | Stop + ANTHROPIC_BASE_URL proxy | Full observability — every API call traced, flushed on session end |
| Git push guard | PreToolUse (git push) | Forces review of commits before push — prevents accidental pushes |
Important: Use$CLAUDE_FILE_PATH(not$file) for the file path variable. Always include atimeoutvalue. Avoid bash-style redirects like2>/dev/null || true— they can cause issues on Windows.
Hook events: SessionStart, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, UserPromptSubmit, PreCompact, PostCompact (v2.1.76), InstructionsLoaded (v2.1.69), Elicitation (v2.1.76), ElicitationResult (v2.1.76), Stop, SubagentStop, Notification, Setup, TeammateIdle, TaskCompleted.
New hooks explained:
InstructionsLoaded— fires when CLAUDE.md or.claude/rules/*.mdfiles are loaded. Enables skill activation patterns (e.g., inject additional context when specific rules load).PostCompact— fires after compaction completes. Use for context renewal: re-inject critical instructions, skill inventories, or project state that may be lost during compaction.Elicitation/ElicitationResult— intercept/override MCP server requests for structured user input.
Double Shot Latte (DSL) — Autonomous Continue Hook
Eliminates unnecessary check-in interruptions during long autonomous sessions. When Claude stops, a Haiku-evaluated prompt decides: does it genuinely need human input, or is it stopping out of habit? If the latter, Claude continues autonomously.
Architecture (two Stop hooks in sequence):
"Stop": [
{
"hooks": [{
"type": "command",
"command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"C:/Users/<you>/.claude/hooks/dsl/double-shot-latte.ps1\"",
"timeout": 8000
}]
},
{
"hooks": [{
"type": "prompt",
"prompt": "DOUBLE SHOT LATTE: Read C:/Users/<you>/.claude/hooks/dsl/decision.txt.\n\nIf it contains THROTTLED: stop and tell the user 'DSL throttled: paused after 3 consecutive stops in 5 minutes — what do you need?'\n\nIf it contains CONTINUE: honestly evaluate whether you genuinely need human input. If you stopped out of habit or caution rather than genuine need — continue working autonomously. Only stop if truly blocked."
}]
}
]`double-shot-latte.ps1` (see hooks/dsl/double-shot-latte.ps1):
- Reads
~/.claude/hooks/dsl/state.jsonfor recent stop timestamps - Cleans entries older than 5 minutes
- Checks if ≥ 3 stops remain (throttle condition)
- Records current stop timestamp
- Writes
CONTINUEorTHROTTLEDtodecision.txt - The prompt hook instructs Claude to read
decision.txtand act accordingly
Throttle logic: 3 stops within 5 minutes → THROTTLED → Claude stops and surfaces to user. This prevents infinite loops.
Key gotcha: Place DSL before session-end and save-lessons hooks in the Stop sequence, but after cleanup hooks like kill-mcp-children. Claude processes all Stop hooks in sequence; DSL's "continue" instruction takes effect after all hooks complete.
Hook types: command (shell), prompt (LLM-based, runs via Haiku), agent (multi-turn with tool access), http (POST to endpoint).
Critical hook gotchas:
type: "prompt"at SessionStart fails ifANTHROPIC_BASE_URLpoints to a custom proxy — use command-only hooks theretype: "command"at Stop can't communicate back to Claude (session is over) — usetype: "prompt"for end-of-session Claude work- PreCompact prompt hooks: never hardcode project-specific paths — use the auto-memory path injected by Claude Code at session start
- Global hooks (
~/.claude/settings.json) run for all projects — keep paths and prompts project-agnostic
Pillar 5: Agents and Subagents
Two types of agents available:
Built-in Subagent Types
Claude Code includes specialized subagents invoked via the Task tool with subagent_type parameter:
| Agent | Purpose | When to Use |
|---|---|---|
| planner | Implementation planning | Complex features, refactoring |
| architect | System design | Architectural decisions |
| tdd-guide | Test-driven development | New features, bug fixes |
| code-reviewer | Code review | After writing code |
| security-reviewer | Security analysis | Before commits |
| build-error-resolver | Fix build errors | When build fails |
| e2e-runner | E2E testing | Critical user flows |
| refactor-cleaner | Dead code cleanup | Code maintenance |
| doc-updater | Documentation | Updating docs |
Usage pattern:
// Invoke built-in subagent
Task(subagent_type: "code-reviewer", prompt: "Review auth.ts for security issues")Proactive usage: Use planner, architect, tdd-guide, and code-reviewer agents automatically without waiting for user prompt when appropriate.
Custom Agents
Create project or domain-specific agents in ~/.claude/agents/ (global) or .claude/agents/ (project-local).
Organize agents by purpose:
~/.claude/agents/
├── engineering/ # Engineering workflow agents (code review, architecture)
├── matts-custom/ # Personal/custom agents (brand-specific, domain-specific)
├── testing/ # Test-focused agents (integration, E2E, load testing)
└── _archived/ # Retired agents (keep for reference, don't delete)Agent file format (~/.claude/agents/engineering/my-agent/AGENT.md):
---
name: my-custom-agent
description: What this agent does
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a [role]. Your responsibilities are:
- [Responsibility 1]
- [Responsibility 2]
[Additional instructions...]Example:
---
name: security-reviewer
description: Expert security auditor for code review
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior security reviewer. Focus on authentication, authorization, input validation, and data handling.Agent Teams (Experimental)
Multi-agent orchestration: Team Lead + Teammates with shared task lists and peer-to-peer messaging.
Enable: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in settings.
When to use what:
- Single agent: Routine tasks, small fixes
- Subagents: Quick parallel research, isolated delegation
- Agent Teams: Discussion, coordination, competing hypotheses, parallel dev across independent files
Critical gotchas:
- No file locking. Enforce strict file ownership between teammates.
- 7x token multiplier. Each teammate is a separate context window.
- Use Sonnet for implementation teammates. Reserve Opus for lead/planning.
- Keep teams to 2-4 agents. Larger teams increase coordination overhead nonlinearly.
- Avoid broadcasts. Use targeted direct messages (broadcasts multiply cost by team size).
Best pattern: Adversarial (implement + review agents). LLMs are significantly better in review mode than implementation mode.
Code Review (March 2026)
Anthropic launched Code Review as a multi-agent PR review capability:
- Multi-agent system that analyzes PRs in parallel, leaving comments directly on GitHub
- Research preview for Team and Enterprise customers
- ~$15-25 per review, ~20 minute completion time
- 54% of PRs receive substantive comments (up from 16% with older approaches)
- Not a skill to install — it's a built-in Claude Code capability
Wave Execution Orchestration
The most powerful multi-agent pattern for complex implementation tasks. Solves context rot — the quality degradation that happens when a single agent accumulates hundreds of tool call results, failed attempts, and intermediate states alongside actual task context. The fix is architectural: keep orchestrators lean, give executors a fresh window.
The pattern:
Orchestrator context budget: ~15%
Each executor context budget: 100% fresh (separate Task invocation)
Step 1: Analyze all plans, build dependency graph
Step 2: Group into waves based on dependencies
Step 3: Execute wave by wave (sequential), parallel within each wave
Example:
Wave 1 (parallel): Plan A + Plan B ← no dependencies
Wave 2 (parallel): Plan C + Plan D ← C needs A, D needs B
Wave 3 (sequential): Plan E ← needs C + DKey design rules:
- Orchestrator stays lean. Discovers plans, analyzes dependencies, spawns agents, collects results — no implementation work itself.
- Executors are disposable. Each gets a fresh context window. They load only what they need for their plan.
- Vertical slices parallelize better than horizontal layers.
- Good:
"Plan 01: User registration end-to-end (model → API → UI)" - Bad:
"Plan 01: All models / Plan 02: All APIs / Plan 03: All UI" - Horizontal plans create cascading dependencies (one long Wave 1 → Wave 2 → Wave 3). Vertical slices can all run in Wave 1.
- File conflict prevention. Plans in the same wave must not touch the same files. If they do, move one to a later wave or merge the plans.
Plan-Checker Loop (quality gate before execution):
Before executing, verify plans actually achieve phase goals. Prevents expensive executor runs on under-specified plans.
1. Spawn planner → produces PLAN.md files
2. Spawn plan-checker → verifies: "Do these plans achieve the phase's stated goals?"
3. If FAIL: return feedback to planner → revise → recheck (max 3 iterations)
4. On PASS: proceed to wave executionXML Task Format:
Structured XML is more reliably followed by Claude than prose instructions. Use for complex multi-task plans where precision matters:
<task type="auto">
<name>Create login endpoint</name>
<files>src/app/api/auth/login/route.ts</files>
<action>
Use jose for JWT (not jsonwebtoken — CommonJS issues).
Validate credentials against users table.
Return httpOnly cookie on success.
</action>
<verify>curl -X POST localhost:3000/api/auth/login returns 200 + Set-Cookie</verify>
<done>Valid credentials return cookie, invalid return 401</done>
</task>Fields:
name— task identifierfiles— exact files to create/modify (reduces hallucinated paths)action— precise instructions with specifics (library choices, constraints, anti-patterns)verify— how to confirm the task worked (shell command, observable behavior)done— definition of done (expected observable outcome)
Pillar 6: Skills and Plugins
Skills = reusable workflows with SKILL.md + optional scripts/templates/references.
Plugins = distributable packages of skills, hooks, agents, and MCP servers.
Skill locations:
~/.claude/skills/— User-global.claude/skills/— Project-level- Plugin
skills/directory — Per plugin
`${CLAUDE_SKILL_DIR}` variable (v2.1.69): Skills can self-reference their own directory in SKILL.md content. Critical for skills with reference files, templates, or scripts. Example: See ${CLAUDE_SKILL_DIR}/references/color-palette.md.
Universal SKILL.md format: The same skill files work across Claude Code, Cursor, Gemini CLI, Codex CLI, Antigravity IDE, and 33+ other agents. Write once, use everywhere.
Skill installation (standardized):
# Official Anthropic skills
npx skills add anthropics/claude-code --skill frontend-design
# Third-party skills (by GitHub repo)
npx skills add browser-use/claude-skill
npx skills add coleam00/excalidraw-diagram-skill --skill excalidraw-diagram
# Antigravity Awesome Skills (1,234+ skills, one command)
npx antigravity-awesome-skills --claude
# List installed skills
npx skills list
# Reload after adding skills (no restart needed)
/reload-pluginsPlugin management:
/plugin marketplace add anthropics/skills
/plugin add /path/to/skill-directory
/plugin marketplace add obra/superpowers-marketplaceKey community plugins: obra/superpowers (20+ battle-tested skills), wshobson/agents (preset workflows), anthropics/skills (official examples).
Antigravity Awesome Skills (22K+ stars, 3.8K+ forks): The largest cross-compatible skill collection. 1,234+ skills organized by category with role-based bundles (Web Wizard, Security Engineer, Essentials). Key starter skills: @brainstorming, @architecture, @debugging-strategies, @api-design-principles, @security-auditor, @create-pr.
Skill discovery sites: aitmpl.com/skills, skills.sh — updated daily with new skills across the ecosystem.
Notable skills worth tracking:
| Skill | What It Does |
|---|---|
| Frontend Design (277K+ installs) | Breaks "distributional convergence" — bold design instead of generic AI aesthetic |
| Browser Use | Live browser automation — navigate, click, fill forms, screenshot |
| Remotion | React-based programmatic video creation (demos, explainers) |
| Shannon | Autonomous AI pen testing — 96% exploit success rate, 50+ vulnerability types |
| Excalidraw | Architecture diagrams from natural language with self-validation rendering loop |
| Valyu | Real-time search across 36+ data sources (SEC, PubMed, FRED, patents) |
Advanced: Event-Driven Skill Injection (Skill Switchboard)
The default skill activation model requires manual slash-command invocation. After context compaction, skills are forgotten entirely. The Skill Switchboard pattern solves this by wiring a PreToolUse hook that reads the file being edited and injects the relevant skill automatically — zero manual invocation required.
Concept (inspired by Agent RuleZ by SpillwaveSolutions):
- Static skill lists = ignored after compaction
- Event-driven injection = deterministic, always-on, zero cognitive load
- AND-logic: file extension + directory pattern must both match
Setup (3 files):
1. `~/.claude/hooks/skill-switchboard/rules.json` — define when each skill fires:
{
"rules": [
{
"name": "csharp-coding-standards",
"enabled": true,
"priority": 50,
"matchers": {
"extensions": [".cs"],
"directories": ["**/Commands/**", "**/Services/**", "**/Controllers/**"]
},
"inject_path": "~/.claude/rules/coding-style.md",
"max_lines": 120
},
{
"name": "angular-component-standards",
"enabled": true,
"priority": 50,
"matchers": {
"extensions": [".ts", ".html", ".scss"],
"directories": ["**/components/**", "**/features/**", "**/store/**"]
},
"inject_path": "~/.claude/rules/coding-style.md",
"max_lines": 120
},
{
"name": "security-sensitive",
"enabled": true,
"priority": 100,
"matchers": {
"extensions": [".cs"],
"directories": ["**/Auth/**", "**/Identity/**", "**/Security/**"]
},
"inject_path": "~/.claude/rules/security.md",
"max_lines": 80
}
]
}2. `~/.claude/hooks/skill-switchboard/switchboard.ps1` — the engine (reads stdin JSON, matches rules, outputs skill content to Claude's context).
3. `~/.claude/settings.json` — wire it as the first PreToolUse hook on Edit|Write:
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "pwsh -NoProfile -ExecutionPolicy Bypass -File \"C:/Users/<you>/.claude/hooks/skill-switchboard/switchboard.ps1\"",
"timeout": 8000
}
]
}Key design decisions:
priority— higher number = injected first (security rules before style rules)max_lines— truncates large SKILL.md files to keep context lean- Deduplication — same file injected once even if matched by multiple rules
- Directory patterns support
**/segment/**glob-style matching - Hook runs before the edit executes — Claude gets context at the right moment
Five activation patterns (from Agent RuleZ architecture):
| Pattern | Trigger | Claude Code Hook |
|---|---|---|
| File-based | Edit/Write on matching extension + directory | PreToolUse command |
| Intent-based | Natural language mentions migration/auth/etc. | UserPromptSubmit prompt |
| Lifecycle | Pre-compaction (re-inject skills inventory) | PreCompact prompt |
| Dynamic | Shell script inspects project state | PreToolUse inject_command |
| Priority | Critical rules forced to top | priority field in rules.json |
PreCompact skill amnesia fix — add to your existing PreCompact prompt hook:
Before compacting, output a brief "Active Skills Available" section listing which
skills are configured in ~/.claude/hooks/skill-switchboard/rules.json so they
survive compaction.Reference: SpillwaveSolutions/agent_rulez on GitHub — comprehensive YAML-based policy engine for Claude Code, OpenCode, and Gemini CLI.
Skill Scope Classification: Global vs Project-Level
Every skill installed globally (~/.claude/skills/) costs tokens on every message in every project — it appears in the system prompt listing regardless of relevance. Project-level skills (.claude/skills/ in the repo root) only appear when working in that project.
The rule: If you wouldn't want a skill listed when working in an unrelated project, it belongs at project level.
Decision framework:
| Question | Global | Project |
|---|---|---|
| Useful in any codebase? | ✅ | ❌ |
| Domain-specific (ComfyUI, YouTube, .NET)? | ❌ | ✅ |
| Used < once a month per project? | ❌ | ✅ |
| Workflow skill (commit, review, plan)? | ✅ | ❌ |
| Content/brand/persona for one client? | ❌ | ✅ |
Global skills — install table:
These are standalone skills installed into ~/.claude/skills/. Each has a source repo for reproducible setup.
| Skill | Source | Install |
|---|---|---|
claude-code-mastery | MCKRUZ/claude-code-mastery | git clone https://github.com/MCKRUZ/claude-code-mastery ~/.claude/skills/claude-code-mastery |
dashboard-creator | mhattingpete/claude-skills-marketplace | npx skills add mhattingpete/claude-skills-marketplace --skill dashboard-creator |
demo-video | MCKRUZ/demo-video-skill | git clone https://github.com/MCKRUZ/demo-video-skill ~/.claude/skills/demo-video |
docx | anthropics/skills | npx skills add anthropics/skills --skill docx |
excalidraw-diagram-generator | coleam00/excalidraw-diagram-skill | npx skills add coleam00/excalidraw-diagram-skill |
find-skills | anthropics/skills | npx skills add anthropics/skills --skill find-skills |
functional-design | MCKRUZ/functional-design | git clone https://github.com/MCKRUZ/functional-design ~/.claude/skills/functional-design |
humanizer | blader/humanizer | git clone https://github.com/blader/humanizer ~/.claude/skills/humanizer |
llm-cost-optimizer | MCKRUZ/llm-cost-optimizer-skill | git clone https://github.com/MCKRUZ/llm-cost-optimizer-skill ~/.claude/skills/llm-cost-optimizer |
pdf | anthropics/skills | npx skills add anthropics/skills --skill pdf |
project-memory | SpillwaveSolutions/project-memory | git clone https://github.com/SpillwaveSolutions/project-memory ~/.claude/skills/project-memory |
security-review | MCKRUZ/security-review-skill | git clone https://github.com/MCKRUZ/security-review-skill ~/.claude/skills/security-review |
shannon | KeygraphHQ/shannon | npx skills add unicodeveloper/shannon |
skeptic | MCKRUZ/skeptic-skill | git clone https://github.com/MCKRUZ/skeptic-skill ~/.claude/skills/skeptic |
slides | MCKRUZ/slides-skill | git clone https://github.com/MCKRUZ/slides-skill ~/.claude/skills/slides |
tdd-workflow | MCKRUZ/tdd-workflow-skill | git clone https://github.com/MCKRUZ/tdd-workflow-skill ~/.claude/skills/tdd-workflow |
visual-explainer | nicobailon/visual-explainer | git clone https://github.com/nicobailon/visual-explainer ~/.claude/skills/visual-explainer |
Built-in capabilities (not standalone skills — provided by plugins or Claude Code itself):
| Capability | Source | How to get |
|---|---|---|
code-review, build-fix, refactor-clean | code-simplifier plugin | /plugin marketplace add anthropics/claude-code |
plan, simplify, learn | code-simplifier plugin | /plugin marketplace add anthropics/claude-code |
deep-project, deep-plan, deep-implement | piercelamb-plugins | /plugin marketplace add piercelamb/plugins |
ctx-doctor, ctx-stats, ctx-upgrade | context-mode plugin | Add marketplace: mksglu/context-mode, then enable |
| Status line (project, model, context %) | claude-hud plugin | Add marketplace: jarrodwatts/claude-hud, then enable |
Project-level skills (install only in relevant projects):
| Skill | Project | Category |
|---|---|---|
comfyui-* (12 skills) | ComfyUI Expert | AI image/video generation |
youtube-* (8 skills), remotion-best-practices | ProjectPrism | Video production |
matt-kruczek-blog-writer, brand, banner-design | personal-brand-assistant | Personal brand |
design-system, ui-ux-pro-max, frontend-design-pro | ArchitectureHelper, matthewkruczek-ai | Frontend design |
consulting-deck, sow-writer, client-intake + 5 more | claude-consultant | Consulting |
grafana-dashboards | openclaw-langfuse | Observability |
pluralsight-skill | pluralsight-skill | Course authoring |
Installing a project-level skill:
# From the project root — creates .claude/skills/<skill-name>/
mkdir -p .claude/skills
cp -r ~/.claude/skills/comfyui-workflow-builder .claude/skills/Or symlink (avoids duplication):
# PowerShell — requires admin or Developer Mode enabled
New-Item -ItemType SymbolicLink -Path ".claude/skills/comfyui-workflow-builder" -Target "$HOME/.claude/skills/comfyui-workflow-builder"After moving, remove from global to eliminate the system prompt overhead:
rm -rf ~/.claude/skills/comfyui-workflow-builderSkill Audit workflow — when invoked as "audit my skills" or "optimize skill scope":
1. List all skills in ~/.claude/skills/ (global installed) 2. Identify the current project type from CLAUDE.md, package.json, or file patterns 3. Classify each globally-installed skill against the decision framework above 4. Propose a migration plan: which to keep global, which to move to this project, which to move to OTHER projects 5. For skills belonging to other projects not currently open: note them for migration (don't act on other projects without confirmation) 6. Offer to execute the moves for the current project
Pillar 7: CI/CD and Automation
Auth CLI (v2.1.41+):
claude auth login # Authenticate (replaces claude --login)
claude auth status # Check auth state (useful in CI)
claude auth logout # Sign outHeadless mode (`-p` / `--print`) — works in PowerShell:
claude -p "Explain the architecture" --output-format json
git diff HEAD~5 | claude -p "Review these changes for bugs"
claude -p "Analyze codebase" --allowedTools "Read,Glob,Grep" --max-turns 10
claude --from-pr 123 # Resume session linked to PR #123GitHub Actions:
name: Claude Code
on:
issue_comment: { types: [created] }
pull_request_review_comment: { types: [created] }
jobs:
claude:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}Parallel workflows with git worktrees (PowerShell):
$project = "C:\CodeRepos\my-project"
$features = @("auth-refactor", "payment-api", "api-restructure")
foreach ($feature in $features) {
git worktree add "$project-$feature" -b "feature-$feature"
Start-Process powershell -ArgumentList "-NoExit", "-Command", "cd '$project-$feature'; claude"
}claude-squad (5.6k stars): TUI for managing multiple sessions with git worktrees. Note: requires tmux (Linux-only). On Windows, use the PowerShell worktree approach above or the Claude Desktop app for parallel sessions.
`/loop` for recurring tasks (v2.1.71):
# Run a prompt every 5 minutes
/loop 5m check the deploy status
# Run a slash command on interval (default: 10m)
/loop /babysit-prsUses CronCreate/CronDelete/CronList scheduling tools. Jobs are session-scoped (gone when Claude exits) and auto-expire after 7 days. Disable with CLAUDE_CODE_DISABLE_CRON env var.
Worktree improvements:
ExitWorktreetool (v2.1.72): leave worktree sessions mid-conversation (keep or remove)worktree.sparsePathssetting (v2.1.76): selective directory checkout for monorepos — only clone relevant directories into the worktree
---
Windows Native Setup (PowerShell)
Claude Code runs natively on Windows via PowerShell. It requires Git Bash under the hood for shell operations, but you launch and interact through PowerShell.
Installation
Prerequisites: 1. Git for Windows — Required. Download from https://git-scm.com/downloads/win. Ensure "Git from the command line" is selected during install (adds to PATH). 2. PowerShell 5.1+ (built-in) or PowerShell 7.x (recommended).
Install Claude Code (PowerShell as Administrator):
# Official installer (recommended — auto-updates)
irm https://claude.ai/install.ps1 | iex
# Or via WinGet (does NOT auto-update)
winget install Anthropic.ClaudeCode
# Verify
claude --version
claude doctorIf `claude` is not recognized after install: 1. The binary installs to C:\Users\<you>\.local\bin\claude.exe 2. Add to PATH: Win+R -> sysdm.cpl -> Advanced -> Environment Variables -> Edit User PATH -> Add C:\Users\<you>\.local\bin 3. Restart terminal
Windows ARM64 support (v2.1.41+):
- Native
win32-arm64binary — no emulation required for the CLI - VS Code extension falls back to x64 via emulation on ARM64 (v2.1.42 fix)
- The
irm https://claude.ai/install.ps1 | iexinstaller auto-detects your architecture
If you get "requires git-bash" error:
# Tell Claude Code where Git Bash lives
[System.Environment]::SetEnvironmentVariable('CLAUDE_CODE_GIT_BASH_PATH', 'C:\Program Files\Git\bin\bash.exe', 'User')
# Restart terminalWindows-Specific Notes
- Config location:
~/.claude/settings.jsonin your Windows home directory (C:\Users\<you>\.claude\) - Updates: Native installer auto-updates. WinGet requires
winget upgrade Anthropic.ClaudeCodemanually. - Image paste limitation:
Win+Shift+Sclipboard paste (Ctrl+V) doesn't work. Use file-based image sharing instead. - Managed settings path (BREAKING v2.1.74): Enterprise managed settings moved from
C:\ProgramData\ClaudeCode\managed-settings.jsontoC:\Program Files\ClaudeCode\managed-settings.json. The old fallback path was removed. - VS Code integration: Install the Claude Code extension. If it can't find Git Bash, set
CLAUDE_CODE_GIT_BASH_PATHas a system env var and restart VS Code. - Hooks use Git Bash: All hook commands in settings.json are executed via Git Bash, so use Unix-style commands (not PowerShell cmdlets) in hooks.
- Windows stability fixes (v2.1.27-2.1.34): Fixed .bashrc handling, console window flashing, OAuth token expiration, proxy settings, bash sandbox errors, Japanese IME support.
---
Essential Slash Commands Quick Reference
| Command | When to use |
|---|---|
/compact | Context above 70% |
/clear | Between unrelated tasks |
/context | Inspect token usage (now gives actionable suggestions) |
/cost | Check session costs |
/init | New project starter CLAUDE.md |
/model | Switch Sonnet/Opus/Haiku |
/effort | Adjust effort level (low/medium/high) |
/resume | Return to previous session |
/plan | Toggle read-only mode (accepts optional description) |
/loop | Recurring task scheduling (e.g., /loop 5m check deploy) |
/mcp | Manage MCP servers within session |
/branch | Fork conversation (was /fork) |
/color | Customize session prompt-bar color |
/debug | Ask Claude to diagnose the current session |
/rename | Rename session (auto-generates name if none given) |
/reload-plugins | Activate plugin/skill changes without restart |
Shift+Tab | Cycle permission modes |
Escape | Stop current operation |
@file | Reference file in prompt |
---
Self-Update Protocol
This skill includes a self-updating research mechanism. When invoked with "update knowledge" or "research latest":
1. Read `references/knowledge-base.md` for the current state of knowledge 2. Read `references/research-sources.md` for where to look 3. Search the web for latest Claude Code updates, community discoveries, and best practices 4. Read `scripts/research-checklist.md` for what to investigate 5. Update `references/knowledge-base.md` with new findings, dated entries 6. Update `references/changelog.md` with what changed and when
The knowledge base follows an append-only log pattern — new findings are added with dates, never overwriting previous entries. This creates a searchable history of how Claude Code has evolved.
---
How to Use This Skill
Quick setup: "Set up Claude Code for my [language/framework] project" Optimize: "Review and optimize my current CLAUDE.md" (paste or reference it) Diagnose: "Why is Claude Code slow/expensive/producing bad output?" Configure: "Set up MCP servers for [workflow]" Automate: "Set up hooks for [quality enforcement]" Scale: "Configure agent teams for [parallel work]" Research: "Update knowledge" or "What's new in Claude Code?"
Always start by understanding the user's current state before prescribing solutions.
---
Reference Files
| File | Contents |
|---|---|
references/knowledge-base.md | Append-only log of Claude Code discoveries and version changes |
references/changelog.md | What changed in this skill and when |
references/settings-templates.md | Production-ready settings.json templates |
references/claude-md-templates.md | CLAUDE.md templates for common project types |
references/troubleshooting.md | Common issues and fixes |
references/rules-directory-pattern.md | Deep dive on the .claude/rules/ pattern |
references/research-sources.md | Where to look when researching Claude Code updates |
references/spec-driven-development.md | Goal-backward planning, project artifacts, UAT loop, parallel research team — for multi-session projects |
{
"name": "claude-code-mastery",
"owner": {
"name": "MCKRUZ",
"email": "matthewkruczek@yahoo.com"
},
"metadata": {
"description": "Production-grade Claude Code harness with quality-gate hooks, 19 curated skills, 9 rules, and a 5-phase development workflow."
},
"plugins": [
{
"name": "claude-code-mastery",
"source": "../",
"description": "The definitive Claude Code setup and configuration package. Includes quality-gate hooks (git safety, config protection, dev-server blocking, console.log warnings), strategic compaction, MCP health checks, verification loop, agent introspection debugging, and 19 curated skills spanning dashboards, presentations, security testing, TDD, and more.",
"version": "3.0.0",
"author": {
"name": "MCKRUZ",
"url": "https://github.com/MCKRUZ"
},
"homepage": "https://github.com/MCKRUZ/claude-code-mastery",
"repository": "MCKRUZ/claude-code-mastery",
"license": "MIT",
"keywords": [
"claude-code",
"harness",
"hooks",
"quality-gates",
"skills",
"windows"
],
"category": "workflow",
"tags": [
"setup",
"configuration",
"hooks",
"skills",
"rules",
"quality-gates",
"security",
"tdd",
"windows-native"
],
"strict": false
}
]
}
{
"name": "claude-code-mastery",
"version": "3.0.0",
"description": "The definitive Claude Code harness. Battle-tested rules, quality-gate hooks, 19 curated skills, and a complete development workflow.",
"author": {
"name": "MCKRUZ",
"url": "https://github.com/MCKRUZ"
},
"license": "MIT",
"repository": "MCKRUZ/claude-code-mastery",
"homepage": "https://github.com/MCKRUZ/claude-code-mastery",
"keywords": [
"claude-code",
"harness",
"hooks",
"quality-gates",
"skills",
"windows"
],
"skills": ["../"],
"commands": ["../commands"]
}
{
"permissions": {
"allow": [
"Bash(git commit:*)",
"Bash(head -5 \"C:/Users/kruz7/.claude/skills/autoresearch-universal/\"*.md)",
"Bash(mkdir -p C:/Users/kruz7/.claude/skills/autoresearch)",
"Bash(cp C:/Users/kruz7/AppData/Local/Temp/autoresearch-skill/SKILL.md C:/Users/kruz7/.claude/skills/autoresearch/SKILL.md)",
"Bash(cp C:/Users/kruz7/AppData/Local/Temp/autoresearch-skill/skills/autoresearch/evaluator-contract.md C:/Users/kruz7/.claude/skills/autoresearch/)",
"Bash(cp C:/Users/kruz7/AppData/Local/Temp/autoresearch-skill/skills/autoresearch/stuck-detection.md C:/Users/kruz7/.claude/skills/autoresearch/)",
"Bash([ -f \"$REPO/skills/$dir/SKILL.md\" ])",
"Bash(mkdir -p /c/Users/kruz7/.claude/hooks/quality-gates)",
"Bash(mkdir -p /c/Users/kruz7/.claude/hooks/mcp-health)",
"Read(//c/Users/kruz7/.claude/hooks//**)",
"Bash(mkdir -p \"/c/Users/kruz7/OneDrive/Documents/Code Repos/MCKRUZ/claude-code-mastery/.claude/skills/verification-loop\")",
"Bash(mkdir -p \"/c/Users/kruz7/OneDrive/Documents/Code Repos/MCKRUZ/claude-code-mastery/.claude/skills/agent-introspection\")"
]
}
}
node_modules/
.env
.env.*
*.log
.DS_Store
Thumbs.db
# APM dependencies
apm_modules/
apm.lock.yaml
# APM-deployed skills (installed via apm install, not source)
.claude/skills/
You are a senior code reviewer. When invoked:
1. Run git diff HEAD~1 to see recent changes 2. Check for bugs, security issues, performance problems 3. Verify test coverage for changed code 4. Check immutability patterns (no direct mutation of objects/arrays) 5. Verify input validation at system boundaries 6. Report findings with severity (critical/warning/info)
Quality Standards
- Functions <50 lines, no deep nesting (>4 levels)
- No console.log or hardcoded values
- Immutable patterns: spread operators (TS), records/with expressions (C#)
- Error handling: Result<T> pattern (C#), catchError in pipes (Angular)
You are a technical documentation writer. When invoked:
1. Analyze the code to understand what it does 2. Write clear, concise documentation 3. Include usage examples where helpful 4. Follow the project's existing doc style
Guidelines
- Lead with what, not why (unless the why is non-obvious)
- Code examples > prose explanations
- Keep README sections short — link to detailed docs
- Use the project's naming conventions in examples
- Don't document obvious things (getters, simple CRUD)
- Focus on: architecture decisions, non-obvious behavior, setup steps, API contracts
You are a security auditor. Focus on:
1. Authentication & authorization — JWT validation (lifetime, clock skew, issuer, audience, signing key), auth on all endpoints 2. Input validation — FluentValidation on DTOs, reactive form validators on frontend 3. Injection risks — SQL (EF Core only, no raw SQL except FromSqlInterpolated), XSS (Angular auto-escapes, DomSanitizer only when unavoidable), CSRF protection 4. Sensitive data exposure — No hardcoded secrets, no secrets in frontend code, error messages don't leak internals 5. Security headers — X-Frame-Options:DENY, X-Content-Type-Options:nosniff, CSP, HSTS 365d 6. Dependency vulnerabilities — Check for known CVEs in packages
Response Protocol
- CRITICAL: Must fix before merge
- WARNING: Should fix, acceptable with justification
- INFO: Best practice suggestion
If you find exposed secrets: flag immediately, recommend rotation, check logs for exploitation.
name: claude-code-mastery
version: 1.9.0
description: >
The definitive Claude Code setup, configuration, and mastery package.
Battle-tested rules, agents, hooks, and 16 curated skills.
author: MCKRUZ
dependencies:
apm:
# Anthropic official skills
- anthropics/skills/skills/docx
- anthropics/skills/skills/pdf
# MCKRUZ custom skills (master branch)
- MCKRUZ/demo-video-skill#master
- MCKRUZ/functional-design#master
- MCKRUZ/llm-cost-optimizer-skill#master
- MCKRUZ/security-review-skill#master
- MCKRUZ/skeptic-skill#master
- MCKRUZ/slides-skill#master
- MCKRUZ/tdd-workflow-skill#master
# Community skills
- mhattingpete/claude-skills-marketplace/visual-documentation-plugin/skills/dashboard-creator
- coleam00/excalidraw-diagram-skill
- blader/humanizer
- SpillwaveSolutions/project-memory
- unicodeveloper/shannon
- nicobailon/visual-explainer
mcp: []
devDependencies:
apm: []
scripts: {}
<!-- nexus:start -->
Nexus Intelligence
Auto-updated by Nexus — do not edit this section manually. Last sync: 2026-04-23
Portfolio
| Project | Description | Tech |
|---|---|---|
| jarvis-stack | — | — |
| personal-brand-assistant | — | — |
| project-avatar | — | — |
| ComfyUI | ComfyUI — the main local ComfyUI installation at E:/ComfyUI-Easy-Install/Co… | — |
| matthewkruczek-ai | matthewkruczek.ai — static personal brand website for Matthew Kruczek (EY M… | — |
| claude-code-mastery (this) | Claude Code Mastery — the definitive Claude Code setup and configuration sk… | — |
| Nexus | Nexus is a local-first cross-project intelligence layer for Claude Code. | — |
| _+32 inactive_ | — | — |
Context from Nexus
Roadmap: Next Features
User-approved feature ideas (2026-03-24):
1. MCP Tool Intelligence Layer — Nexus sits on mcp-hub, learns which tools succeed/fail per project, i… Tags: roadmap, features, mcp-hub, planning
Backlog: Show all active MCP servers in Claude Config tab
The Claude Config dashboard page only shows MCP servers from settings.json/settings.local.json, not the full set of running servers (plugins + projec… Tags: backlog, dashboard, mcp, claude-config
Token Budget Optimization Session - 2026-03-18
Token Budget Optimizations Applied
1. Portfolio Table Filter (claude-md-sync.ts)
- Before: All 35+ projects listed in every CLAUDE.md sync (~…
Tags: token-budget, skills, portfolio, optimization
Session Insights - 2026-03-17
Session Insights - 2026-03-17
Scope: 20 sessions, ~1 month, 670 total messages, 33.5 avg msgs/session
Top Projects
1. OpenClaw — 5 s… Tags: insights, sessions, analytics
OpenClaw Ollama Fallback & Stop Hook JSON Validation Fix
(1) OpenClaw agent fallback chain requires tool-capable models; dolphin-llama3 doesn't support tools so was removed; llama3.1:8b being pulled as Olla… Tags: openclaw, ollama, hooks, bug-fix
Recorded Decisions
- [security] Sanitize and rotate credentials after eval runs that may expose secrets
During test case TC-003, a real GitHub PAT was exposed in skill output. Established practice to rotate credentials and document secret exposure risks in eval framework.
- [security] Sanitize eval test harness to prevent credential leakage from settings files
Eval run exposed GitHub PAT token when skill accessed actual settings.json during MCP config test
- [security] Include platform-aware syntax validation in evaluations — specifically test Win…
TC-005 and TC-003 explicitly validate Windows-compatible output; 15% of benchmark criteria allocated to platform awareness
- [architecture] Add failure-mode test cases for adversarial input and edge cases before finaliz…
After initial 5 test cases passed at 100%, added TC-006, TC-007, TC-008 to test adversarial users, contradictory platform info, and cold-start scenarios. Discovered that robustness under adversarial conditions should be weighted (10%).
- [architecture] Use anchored, objective assertion types for eval scoring instead of subjective …
Initial eval used vague assertions like 'sequence_check' and subjective descriptions. Refactored to use concrete assertion types: contains, regex, question_before_code (line position), json_valid, token_limit to reduce scoring ambiguity.
Cross-project rule: Before making decisions that affect shared concerns (APIs, auth, data formats, deployment) or asking the user for server/SSH/infrastructure details, run nexus_query to check for existing decisions, notes, and conflicts across the portfolio.[Nexus: run `nexus query` to search full knowledge base] <!-- nexus:end -->
Build and Fix
Incrementally fix TypeScript and build errors with verification after each fix.
Workflow
1. Run build: npm run build or pnpm build
2. Parse error output:
- Group by file
- Sort by severity
3. For each error:
- Show error context (5 lines before/after)
- Explain the issue
- Propose fix
- Apply fix
- Re-run build
- Verify error resolved
4. Stop if:
- Fix introduces new errors
- Same error persists after 3 attempts
- User requests pause
5. Show summary:
- Errors fixed
- Errors remaining
- New errors introduced
Important
Fix one error at a time for safety. Always verify the build after each fix before moving to the next error.
Code Review
Perform a comprehensive security and quality review of uncommitted changes.
Workflow
1. Get changed files: git diff --name-only HEAD
2. For each changed file, check for:
Security Issues (CRITICAL)
- Hardcoded credentials, API keys, tokens
- SQL injection vulnerabilities
- XSS vulnerabilities
- Missing input validation
- Insecure dependencies
- Path traversal risks
Code Quality (HIGH)
- Functions > 50 lines
- Files > 800 lines
- Nesting depth > 4 levels
- Missing error handling
- console.log statements
- TODO/FIXME comments
- Missing JSDoc for public APIs
Best Practices (MEDIUM)
- Mutation patterns (use immutable instead)
- Emoji usage in code/comments
- Missing tests for new code
- Accessibility issues (a11y)
Output Format
3. Generate report with:
- Severity: CRITICAL, HIGH, MEDIUM, LOW
- File location and line numbers
- Issue description
- Suggested fix
Gate
4. Block commit if CRITICAL or HIGH issues found — list all issues that must be resolved before merging.
Never approve code with security vulnerabilities.
E2E Command
Generate, maintain, and execute end-to-end tests using Playwright.
Workflow
1. Generate Test Journeys - Create Playwright tests for user flows 2. Run E2E Tests - Execute tests across browsers 3. Capture Artifacts - Screenshots, videos, traces on failures 4. Generate Report - HTML reports and JUnit XML 5. Identify Flaky Tests - Quarantine unstable tests
When to Use
Use /e2e when:
- Testing critical user journeys (login, trading, payments)
- Verifying multi-step flows work end-to-end
- Testing UI interactions and navigation
- Validating integration between frontend and backend
- Preparing for production deployment
Process
1. Analyze user flow and identify test scenarios 2. Generate Playwright test using Page Object Model pattern 3. Run tests across multiple browsers (Chrome, Firefox, Safari) 4. Capture failures with screenshots, videos, and traces 5. Generate report with results and artifacts 6. Identify flaky tests and recommend fixes
Test Artifacts
On All Tests:
- HTML Report with timeline and results
- JUnit XML for CI integration
On Failure Only:
- Screenshot of the failing state
- Video recording of the test
- Trace file for debugging (step-by-step replay)
- Network logs
- Console logs
Flaky Test Detection
If a test fails intermittently: 1. Report the pass rate (e.g., 7/10 runs) 2. Identify common failure cause (timeout, race condition, animation) 3. Recommend fix (explicit wait, increased timeout, race condition fix) 4. Suggest quarantine with test.fixme() until fixed
Browser Configuration
Tests run on multiple browsers by default:
- Chromium (Desktop Chrome)
- Firefox (Desktop)
- WebKit (Desktop Safari)
- Mobile Chrome (optional)
Configure in playwright.config.ts to adjust browsers.
Best Practices
DO:
- Use Page Object Model for maintainability
- Use
data-testidattributes for selectors - Wait for API responses, not arbitrary timeouts
- Test critical user journeys end-to-end
- Run tests before merging to main
- Review artifacts when tests fail
DON'T:
- Use brittle selectors (CSS classes can change)
- Test implementation details
- Run tests against production
- Ignore flaky tests
- Skip artifact review on failures
- Test every edge case with E2E (use unit tests)
Quick Commands
# Run all E2E tests
npx playwright test
# Run specific test file
npx playwright test tests/e2e/markets/search.spec.ts
# Run in headed mode (see browser)
npx playwright test --headed
# Debug test
npx playwright test --debug
# Generate test code
npx playwright codegen http://localhost:3000
# View report
npx playwright show-reportCI/CD Integration
# .github/workflows/e2e.yml
- name: Install Playwright
run: npx playwright install --with-deps
- name: Run E2E tests
run: npx playwright test
- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v3
with:
name: playwright-report
path: playwright-report/Integration with Other Commands
- Use
/planto identify critical journeys to test - Use
/tddfor unit tests (faster, more granular) - Use
/e2efor integration and user journey tests - Use
/code-reviewto verify test quality
/learn - Extract Reusable Patterns
Analyze the current session and extract any patterns worth saving as reusable skills.
Trigger
Run /learn at any point during a session when you've solved a non-trivial problem.
What to Extract
Look for:
1. Error Resolution Patterns
- What error occurred?
- What was the root cause?
- What fixed it?
- Is this reusable for similar errors?
2. Debugging Techniques
- Non-obvious debugging steps
- Tool combinations that worked
- Diagnostic patterns
3. Workarounds
- Library quirks
- API limitations
- Version-specific fixes
4. Project-Specific Patterns
- Codebase conventions discovered
- Architecture decisions made
- Integration patterns
Output Format
Create a skill file at skills/learned/[pattern-name].md:
# [Descriptive Pattern Name]
**Extracted:** [Date]
**Context:** [Brief description of when this applies]
## Problem
[What problem this solves - be specific]
## Solution
[The pattern/technique/workaround]
## Example
[Code example if applicable]
## When to Use
[Trigger conditions - what should activate this skill]Process
1. Review the session for extractable patterns 2. Identify the most valuable/reusable insight 3. Draft the skill file 4. Ask user to confirm before saving 5. Save to skills/learned/
Notes
- Don't extract trivial fixes (typos, simple syntax errors)
- Don't extract one-time issues (specific API outages, etc.)
- Focus on patterns that will save time in future sessions
- Keep skills focused — one pattern per skill
Plan Command
Create a comprehensive implementation plan before writing any code.
Workflow
1. Restate Requirements - Clarify what needs to be built 2. Identify Risks - Surface potential issues and blockers 3. Create Step Plan - Break down implementation into phases 4. Wait for Confirmation - MUST receive user approval before proceeding
When to Use
Use /plan when:
- Starting a new feature
- Making significant architectural changes
- Working on complex refactoring
- Multiple files/components will be affected
- Requirements are unclear or ambiguous
Process
1. Analyze the request and restate requirements in clear terms 2. Break down into phases with specific, actionable steps 3. Identify dependencies between components 4. Assess risks and potential blockers 5. Estimate complexity (High/Medium/Low) 6. Present the plan and WAIT for explicit confirmation
Output Format
# Implementation Plan: [Feature Name]
## Requirements Restatement
- [Clear bullet points of what needs to be built]
## Implementation Phases
### Phase 1: [Name]
- [Specific actionable steps]
- [Files to create/modify]
### Phase 2: [Name]
- [Steps]
## Dependencies
- [External services, libraries, etc.]
## Risks
- HIGH: [Critical risks]
- MEDIUM: [Notable risks]
- LOW: [Minor risks]
## Estimated Complexity: [HIGH/MEDIUM/LOW]
- [Time estimates per phase]
**WAITING FOR CONFIRMATION**: Proceed with this plan? (yes/no/modify)Important
CRITICAL: Do NOT write any code until the user explicitly confirms the plan with "yes", "proceed", or similar affirmative response.
If the user wants changes, they can respond with:
- "modify: [changes]"
- "different approach: [alternative]"
- "skip phase X and do phase Y first"
Integration with Other Commands
After planning:
- Use
/tddto implement with test-driven development - Use
/build-fixif build errors occur - Use
/code-reviewto review completed implementation
Refactor Clean
Safely identify and remove dead code with test verification at every step.
Workflow
1. Run dead code analysis tools:
knip— Find unused exports and filesdepcheck— Find unused dependenciests-prune— Find unused TypeScript exports
2. Generate comprehensive report in .reports/dead-code-analysis.md
3. Categorize findings by severity:
- SAFE: Test files, unused utilities
- CAUTION: API routes, components
- DANGER: Config files, main entry points
4. Propose safe deletions only
5. Before each deletion:
- Run full test suite
- Verify tests pass
- Apply change
- Re-run tests
- Rollback if tests fail
6. Show summary of cleaned items
Important
Never delete code without running tests first. Only propose deletions categorized as SAFE. Present CAUTION items for user review but do not delete automatically.
/sdlc-setup - Interactive Setup Wizard
Initialize SDLC lifecycle management for a project.
Workflow
Step 1: Check Existing Setup
Look for .sdlc/state.yaml in the current directory.
- If exists: warn the user that SDLC is already initialized. Ask if they want to view status (
/sdlc) or re-initialize (destructive -- requires confirmation). - If not exists: proceed with setup.
Step 2: Profile Selection
List available profiles:
- microsoft-enterprise — C#/.NET 8 + Angular 17 + Azure, SOC 2 compliance, 80% coverage minimum, TDD required
- starter — Minimal profile, no compliance gates, quick start for any stack
Ask the user to select a profile.
Step 3: Project Configuration
Ask the user for:
- Project name (default: current directory name)
- Confirm the selected profile settings are appropriate
Step 4: Initialize .sdlc/
Create the following directory structure:
.sdlc/
state.yaml # Phase tracking (Phase 0: Discovery active)
profile.yaml # Frozen copy of selected profile
constitution.md # Project constitution
artifacts/ # Per-phase artifact directories (00-09)If an init script is available (e.g., init_project.py), run it:
python scripts/init_project.py \
--profile profiles/<selected-profile>/profile.yaml \
--target . \
--name "<project-name>"Otherwise, create the directory structure manually.
Step 5: Update CLAUDE.md / Project Instructions
Read the profile's claude-md-template.md and append its contents to the project's instruction file:
- If project instructions exist: append the SDLC section
- If they don't exist: create with the SDLC section
Step 6: Confirmation
Display:
SDLC initialized successfully!
Profile: <profile-id>
Phase: 0 - Discovery (active)
Artifacts: .sdlc/artifacts/00-discovery/
Next steps:
1. Run /sdlc to see Phase 0 guidance
2. Create your problem statement in .sdlc/artifacts/00-discovery/problem-statement.md
3. Check exit criteria when ready
4. Advance to Phase 1 when criteria are metStep 7: Validate
Run the profile validator to confirm the setup is healthy (if available):
python scripts/validate_profile.py .sdlc/profile.yamlError Handling
- If profile validation fails: show errors and suggest fixes
- If directory permissions prevent creation: report the error clearly
/sdlc - Phase Guidance
Show guidance for the current SDLC phase including what to do, which skills to use, and what artifacts to produce.
Workflow
1. Locate state file: Look for .sdlc/state.yaml in the current project directory. If not found, tell the user to run /sdlc-setup first and exit.
2. Read state: Load .sdlc/state.yaml to get current_phase.
3. Load phase definition: Read the phase definition file from phases/XX-phasename.md (where XX is the zero-padded phase number).
4. Load profile: Read .sdlc/profile.yaml to get stack and quality configuration.
5. Display phase context:
Header
Phase {N}: {Name}
Profile: {profile_id}Purpose
One-line description of this phase's goal.
What to Do Next
Based on the phase workflow steps and current artifact state:
- List the next actionable step
- Reference the specific skill/command to use
- Example: "Run
/planto decompose your problem statement into requirements"
Required Artifacts
List artifacts needed to pass exit gates, with status:
- [x] artifact.md (exists, 1.2KB)
- [ ] other-artifact.md (missing)
Skills to Use
List primary and secondary skills for this phase with brief description.
Exit Criteria
Summarize what must be true to advance (from phase definition's exit criteria).
Quick Commands
/sdlc-setup - Initialize SDLC for a project6. Compliance callout: If the profile has compliance frameworks, note any compliance-specific requirements for this phase.
7. Be concise. The phase definition file has full details -- this command shows the actionable summary, not the full document.
Arguments
- No arguments: show guidance for current phase
<phase-number>: show guidance for a specific phase (e.g.,/sdlc 3)
SDLC Sub-Commands
The full SDLC lifecycle includes these additional sub-commands (not yet ported to Cursor -- available in Claude Code):
| Sub-Command | Purpose |
|---|---|
/sdlc-gate | Run exit criteria check for the current phase |
/sdlc-next | Advance to the next phase (runs gate check first) |
/sdlc-phase-report | Generate an HTML report for the current phase |
/sdlc-status | View full SDLC progress dashboard |
These can be manually replicated by checking .sdlc/state.yaml and the corresponding phase definition files.
TDD Command
Enforce test-driven development methodology for the requested feature or fix.
Workflow
1. Scaffold Interfaces - Define types/interfaces first 2. Generate Tests First - Write failing tests (RED) 3. Implement Minimal Code - Write just enough to pass (GREEN) 4. Refactor - Improve code while keeping tests green (REFACTOR) 5. Verify Coverage - Ensure 80%+ test coverage
When to Use
Use /tdd when:
- Implementing new features
- Adding new functions/components
- Fixing bugs (write test that reproduces bug first)
- Refactoring existing code
- Building critical business logic
TDD Cycle
RED -> GREEN -> REFACTOR -> REPEAT
RED: Write a failing test
GREEN: Write minimal code to pass
REFACTOR: Improve code, keep tests passing
REPEAT: Next feature/scenarioProcess
1. Define interfaces for inputs/outputs 2. Write tests that will FAIL (because code doesn't exist yet) 3. Run tests and verify they fail for the right reason 4. Write minimal implementation to make tests pass 5. Run tests and verify they pass 6. Refactor code while keeping tests green 7. Check coverage and add more tests if below 80%
TDD Best Practices
DO:
- Write the test FIRST, before any implementation
- Run tests and verify they FAIL before implementing
- Write minimal code to make tests pass
- Refactor only after tests are green
- Add edge cases and error scenarios
- Aim for 80%+ coverage (100% for critical code)
DON'T:
- Write implementation before tests
- Skip running tests after each change
- Write too much code at once
- Ignore failing tests
- Test implementation details (test behavior)
- Mock everything (prefer integration tests)
Test Types to Include
Unit Tests (Function-level):
- Happy path scenarios
- Edge cases (empty, null, max values)
- Error conditions
- Boundary values
Integration Tests (Component-level):
- API endpoints
- Database operations
- External service calls
- Components with hooks/services
E2E Tests (use /e2e command):
- Critical user flows
- Multi-step processes
- Full stack integration
Coverage Requirements
- 80% minimum for all code
- 100% required for:
- Financial calculations
- Authentication logic
- Security-critical code
- Core business logic
Important
MANDATORY: Tests must be written BEFORE implementation. The TDD cycle is:
1. RED - Write failing test 2. GREEN - Implement to pass 3. REFACTOR - Improve code
Never skip the RED phase. Never write code before tests.
Integration with Other Commands
- Use
/planfirst to understand what to build - Use
/tddto implement with tests - Use
/build-fixif build errors occur - Use
/code-reviewto review implementation - Use
/test-coverageto verify coverage
Test Coverage
Analyze test coverage and generate missing tests to reach the 80% minimum threshold.
Workflow
1. Run tests with coverage: npm test -- --coverage or pnpm test --coverage
2. Analyze coverage report (coverage/coverage-summary.json)
3. Identify files below 80% coverage threshold
4. For each under-covered file:
- Analyze untested code paths
- Generate unit tests for functions
- Generate integration tests for APIs
- Generate E2E tests for critical flows
5. Verify new tests pass
6. Show before/after coverage metrics
7. Ensure project reaches 80%+ overall coverage
Focus Areas
- Happy path scenarios
- Error handling
- Edge cases (null, undefined, empty)
- Boundary conditions
Update Codemaps
Analyze the codebase structure and update architecture documentation.
Workflow
1. Scan all source files for imports, exports, and dependencies
2. Generate token-lean codemaps in the following format:
codemaps/architecture.md— Overall architecturecodemaps/backend.md— Backend structurecodemaps/frontend.md— Frontend structurecodemaps/data.md— Data models and schemas
3. Calculate diff percentage from previous version
4. If changes > 30%, request user approval before updating
5. Add freshness timestamp to each codemap
6. Save reports to .reports/codemap-diff.txt
Focus
Use TypeScript/Node.js for analysis. Focus on high-level structure, not implementation details. Keep codemaps token-lean so they can be included in AI context without consuming excessive tokens.
Update Documentation
Sync documentation from source-of-truth files to keep docs accurate and current.
Workflow
1. Read package.json scripts section
- Generate scripts reference table
- Include descriptions from comments
2. Read .env.example
- Extract all environment variables
- Document purpose and format
3. Generate docs/CONTRIB.md with:
- Development workflow
- Available scripts
- Environment setup
- Testing procedures
4. Generate docs/RUNBOOK.md with:
- Deployment procedures
- Monitoring and alerts
- Common issues and fixes
- Rollback procedures
5. Identify obsolete documentation:
- Find docs not modified in 90+ days
- List for manual review
6. Show diff summary
Source of Truth
Single source of truth: package.json and .env.example. All generated documentation derives from these files.
Global Rules for Cursor
Paste this into: Cursor Settings > General > Rules for AI
Project-specific rules go in .cursor/rules/*.mdc files per repo
Philosophy
- Simplicity over cleverness. The right solution is the one easiest to understand next month.
- Finish the job. No TODOs, partial implementations, or "exercise for the reader" gaps.
- Replace, don't deprecate. When something is wrong, fix it — don't add a compatibility layer.
- Verify at every level. If you made a change, prove it works before moving on.
- Bias toward action. When the path is clear, execute. Don't ask for permission on obvious next steps.
- YAGNI. Don't build for hypothetical futures. Three similar lines beat a premature abstraction.
Our Working Relationship
- We're colleagues. Talk to me like a senior engineer, not a customer.
- Be direct, not diplomatic. "This won't work because X" beats "That's a great idea, but perhaps..."
- Never open with "You're absolutely right!", "Great question!", or "Absolutely!". Just answer.
- Push back when I'm wrong. If my approach has a flaw, say so before implementing it.
- Don't apologize for being thorough or for catching my mistakes — that's the job.
- When you're uncertain, say so plainly. "I'm not sure" is always better than a confident guess.
- If I'm heading toward a bad decision, flag it clearly. Don't just go along with it.
Autonomy Framework
Green — Just Do It
- Fix lint errors, type errors, broken imports
- Run tests, format code, fix failing builds
- Single-function bug fixes with obvious causes
- Git operations I explicitly asked for
- Reading files to understand context
Yellow — Propose First, Then Execute
- Multi-file refactors or architectural changes
- Adding new dependencies or packages
- Creating new files or directories
- Changes to build/CI configuration
- Anything that touches auth, payments, or user data
Red — Always Ask, Never Assume
- Deleting files, branches, or data
- Force-pushing or rewriting git history
- Changes to production config, infrastructure, or secrets
- Rewriting working code that isn't broken
- Scope expansion beyond what was requested
Cross-Project Conventions
- Immutability first: spread operators (TS), records/IReadOnlyList (C#), never mutate in place.
- Validate at system boundaries, trust internal code.
- 80% test coverage minimum on new code.
- No console.log, no hardcoded secrets, no deep nesting (>4 levels).
- Functions under 50 lines. Files under 400 lines.
- Prefer editing existing files over creating new ones.
Preferred Tools
- Git/GitHub:
git,ghfor all GitHub operations - .NET:
dotnetCLI for build/test/run - Node:
npm/npx(not yarn, not pnpm) - Angular:
ngCLI - Python:
py/python,pytestfor tests - Azure:
azCLI,bicepfor IaC
Planning & Execution
- Enter plan mode for any non-trivial task (3+ files or unclear requirements).
- Use subagents for independent, parallelizable work — don't do sequentially what can run concurrently.
- When I report a bug, don't start by trying to fix it. Instead, start by writing a test that reproduces the bug. Then, have subagents try to fix the bug and prove it with a passing test.
- After a mediocre fix, ask: "Is there a more elegant solution?" Don't settle on the first thing that passes.
Response Style
- Lead with the answer, not the reasoning.
- Skip trailing summaries — I read the diff.
- Use file_path:line_number when referencing code.
- Only add comments where logic isn't self-evident.
- Don't narrate what you're about to do — just do it.
- When presenting options, lead with your recommendation.
Scope Discipline
- Don't add features not explicitly requested.
- Don't refactor code unrelated to the current task.
- Don't add docstrings, comments, or type annotations to code you didn't change.
- Don't create wrapper abstractions for one-time operations.
- Don't add error handling for scenarios that can't happen.
- Don't suggest improvements I didn't ask for.
<#
.SYNOPSIS
Installs Claude Code configuration into Cursor.
.DESCRIPTION
Copies skills (global), project rules, subagents, and commands
from the cursor-export directory into the appropriate Cursor locations.
Skills -> ~/.agents/skills/<name>/SKILL.md (global, shared ecosystem)
Rules -> <project>/.cursor/rules/*.mdc
Subagents -> <project>/.cursor/agents/*.md
Commands -> <project>/.cursor/rules/commands/*.mdc (as Manual rules, invoke with @)
.PARAMETER ProjectPath
Target project directory to install project-level configs into.
If omitted, only global skills are installed.
.PARAMETER SkillsOnly
Only install global skills (no project-level configs).
.PARAMETER DryRun
Show what would be done without making changes.
.EXAMPLE
.\install-cursor.ps1 -ProjectPath "C:\my\project"
.EXAMPLE
.\install-cursor.ps1 -SkillsOnly
.EXAMPLE
.\install-cursor.ps1 -ProjectPath "C:\my\project" -DryRun
#>
param(
[string]$ProjectPath,
[switch]$SkillsOnly,
[switch]$DryRun
)
$ErrorActionPreference = "Stop"
$ExportDir = $PSScriptRoot
$AgentsSkillsDir = Join-Path (Join-Path $HOME ".agents") "skills"
$Installed = @{ Skills = 0; Rules = 0; Subagents = 0; Commands = 0 }
function Write-Step($msg) { Write-Host " [+] $msg" -ForegroundColor Green }
function Write-Skip($msg) { Write-Host " [-] $msg" -ForegroundColor Yellow }
function Write-Info($msg) { Write-Host " [i] $msg" -ForegroundColor Cyan }
# --- SKILLS (Global) ----------------------------------------------------------
Write-Host ""
Write-Host "=== Installing Skills to ~/.agents/skills/ ===" -ForegroundColor White
$skillsSource = Join-Path $ExportDir "skills"
if (Test-Path $skillsSource) {
Get-ChildItem $skillsSource -Filter "*.md" | ForEach-Object {
$skillName = $_.BaseName
$targetDir = Join-Path $AgentsSkillsDir $skillName
$targetFile = Join-Path $targetDir "SKILL.md"
if (-not $DryRun) {
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
Copy-Item $_.FullName $targetFile -Force
}
Write-Step "$skillName -> $targetDir"
$Installed.Skills++
}
} else {
Write-Skip "No skills directory found at $skillsSource"
}
if ($SkillsOnly) {
Write-Host ""
Write-Host "=== Summary ===" -ForegroundColor White
Write-Info "$($Installed.Skills) skills installed"
Write-Host ""
Write-Host " Don't forget to paste global-rules.md into Cursor > Settings > General > Rules for AI" -ForegroundColor Yellow
exit 0
}
# --- PROJECT-LEVEL CONFIGS ----------------------------------------------------
if (-not $ProjectPath) {
Write-Host ""
Write-Host "No -ProjectPath specified. Use -ProjectPath to install project-level configs." -ForegroundColor Yellow
Write-Host "Example: .\install-cursor.ps1 -ProjectPath 'C:\my\project'" -ForegroundColor Yellow
exit 0
}
if (-not (Test-Path $ProjectPath)) {
Write-Error "Project path does not exist: $ProjectPath"
exit 1
}
$cursorDir = Join-Path $ProjectPath ".cursor"
$cursorRulesDir = Join-Path $cursorDir "rules"
$cursorAgentsDir = Join-Path $cursorDir "agents"
$cursorCommandsDir = Join-Path (Join-Path $cursorDir "rules") "commands"
# --- RULES --------------------------------------------------------------------
Write-Host ""
Write-Host "=== Installing Rules to .cursor/rules/ ===" -ForegroundColor White
$rulesSource = Join-Path $ExportDir "project-rules"
if (Test-Path $rulesSource) {
if (-not $DryRun) {
New-Item -ItemType Directory -Path $cursorRulesDir -Force | Out-Null
}
Get-ChildItem $rulesSource -Filter "*.mdc" | ForEach-Object {
$targetFile = Join-Path $cursorRulesDir $_.Name
if (-not $DryRun) {
Copy-Item $_.FullName $targetFile -Force
}
Write-Step "$($_.Name) -> .cursor/rules/"
$Installed.Rules++
}
} else {
Write-Skip "No project-rules directory found"
}
# --- SUBAGENTS ----------------------------------------------------------------
Write-Host ""
Write-Host "=== Installing Subagents to .cursor/agents/ ===" -ForegroundColor White
$agentsSource = Join-Path $ExportDir "subagents"
if (Test-Path $agentsSource) {
if (-not $DryRun) {
New-Item -ItemType Directory -Path $cursorAgentsDir -Force | Out-Null
}
Get-ChildItem $agentsSource -Filter "*.md" | ForEach-Object {
$targetFile = Join-Path $cursorAgentsDir $_.Name
if (-not $DryRun) {
Copy-Item $_.FullName $targetFile -Force
}
Write-Step "$($_.Name) -> .cursor/agents/"
$Installed.Subagents++
}
} else {
Write-Skip "No subagents directory found"
}
# --- COMMANDS (as Manual rules) -----------------------------------------------
Write-Host ""
Write-Host "=== Installing Commands as Manual Rules to .cursor/rules/commands/ ===" -ForegroundColor White
Write-Info "Cursor does not have file-based commands. These are installed as Manual rules -- invoke with @ in chat."
$commandsSource = Join-Path $ExportDir "commands"
if (Test-Path $commandsSource) {
if (-not $DryRun) {
New-Item -ItemType Directory -Path $cursorCommandsDir -Force | Out-Null
}
Get-ChildItem $commandsSource -Filter "*.md" | ForEach-Object {
$mdcName = $_.BaseName + ".mdc"
$targetFile = Join-Path $cursorCommandsDir $mdcName
$content = Get-Content $_.FullName -Raw
if ($content -match "^---") {
$content = $content -replace "(?m)^alwaysApply:.*$", ""
$content = $content -replace "(?m)^globs:.*$", ""
}
if (-not $DryRun) {
Set-Content -Path $targetFile -Value $content -Encoding UTF8
}
Write-Step "$($_.BaseName) -> .cursor/rules/commands/$mdcName"
$Installed.Commands++
}
} else {
Write-Skip "No commands directory found"
}
# --- SUMMARY ------------------------------------------------------------------
Write-Host ""
Write-Host "=== Summary ===" -ForegroundColor White
if ($DryRun) {
Write-Host " DRY RUN -- no files were written" -ForegroundColor Yellow
}
Write-Info "$($Installed.Skills) skills installed (global)"
Write-Info "$($Installed.Rules) rules installed to $cursorRulesDir"
Write-Info "$($Installed.Subagents) subagents installed to $cursorAgentsDir"
Write-Info "$($Installed.Commands) commands installed as manual rules to $cursorCommandsDir"
Write-Host ""
Write-Host "=== Manual Steps Required ===" -ForegroundColor Yellow
Write-Host " 1. Open Cursor > Settings > General > Rules for AI" -ForegroundColor Yellow
Write-Host " 2. Paste the contents of: $ExportDir\global-rules.md" -ForegroundColor Yellow
Write-Host " 3. Verify skills appear in: Cursor > Settings > Rules, Skills, Subagents > Skills" -ForegroundColor Yellow
Write-Host " 4. Ensure 'Include third party Plugins, Skills' toggle is ON" -ForegroundColor Yellow
Write-Host ""
---
description: Coding style conventions for C#, TypeScript, Angular, and Python projects
alwaysApply: true
---
# Coding Style
## Immutability (CRITICAL)
- C#: IReadOnlyList<T>/IReadOnlyDictionary<K,V> for public surfaces, readonly arrays for private backing fields, init-only properties for DTOs/config. Use records for simple value types, but NOT for polymorphic hierarchies (use classes with factory methods instead).
- TypeScript: spread operators, never mutate objects/arrays. `{ ...obj, key }` and `[...arr, item]`.
- NgRx reducers: always return new state objects.
## File Organization
- Clean Architecture with type-organized layers (Exceptions, Extensions, Interfaces, Models, Services — not feature folders within layers).
- Many small files > few large files. Most files under 150 lines, 400 max.
- High cohesion, low coupling. One class per file.
## Naming
- C#: PascalCase (classes/methods/props), `_camelCase` (private fields), camelCase (locals/params), `I` prefix for interfaces.
- TypeScript: PascalCase (types/classes), camelCase (vars/funcs), kebab-case (files).
- Python: snake_case (functions/variables), PascalCase (classes), UPPER_SNAKE_CASE (constants).
## Error Handling
- C#: Result<T> for expected failures (validation, auth, business rules). Exceptions only for truly exceptional conditions. Factory methods: `Result<T>.Success(value)`, `Result<T>.Fail(message)`, `Result.ValidationFailure(errors)`.
- Angular: catchError in pipes, use logger service (no console.log), notify user.
- Always: structured JSON logging, never swallow errors silently.
## Validation
- C#: FluentValidation on all DTOs, auto-discovered via assembly scanning, applied through MediatR pipeline behavior. Parallel validation with `Task.WhenAll`.
- Angular: Reactive Forms with validators.
- Validate at system boundaries only — trust internal code.
## Dependency Injection
- Each layer provides `DependencyInjection.cs` with `Add*Dependencies()` extension methods.
- Use keyed DI (`AddKeyedSingleton/Transient`) for extensible registrations (tools, connectors).
- MediatR pipeline behavior order matters — document registration order in DI.
## C# Project Defaults
- `<ImplicitUsings>enable</ImplicitUsings>` and `<Nullable>enable</Nullable>` in all .csproj files.
- Options pattern with `IOptionsMonitor<T>` for configuration. Strongly-typed config hierarchies.
---
description: Git commit message conventions, PR workflow, and planning approach
alwaysApply: true
---
# Git & Workflow
## Planning
- Plan before coding on any non-trivial task (3+ files or unclear requirements).
- For complex features (5+ files, new services): outline the approach and get approval before implementing.
- Review your own work before marking anything as done.
## Commit Messages
Format: `type: description` (feat, fix, refactor, docs, test, chore, perf, ci)
- Imperative mood, lowercase, no period at end
- Under 72 characters
- Body optional — explain "why" not "what" when included
## PR Workflow
1. Analyze full commit history with `git diff [base-branch]...HEAD`
2. Draft comprehensive summary with test plan
3. Push with `-u` flag if new branch
4. PR title under 70 characters — use description for details
## Branch Hygiene
- Never force-push to main/master
- Never commit secrets, .env files, or credentials
- Use feature branches for all work
---
description: Context window management, research limits, and build troubleshooting approach
alwaysApply: true
---
# Performance
## Context Window
- Avoid last 20% for large refactoring or multi-file features. Single-file edits and docs are fine near the limit.
- When context is getting long, finish current work cleanly rather than starting new complex tasks.
## Research Time Limits
- If a single site or source takes more than 5 minutes to fetch or return useful results, abandon that source and move on.
- One or two attempts per source max, then pivot to the next.
## Build Troubleshooting
- Build fails → analyze the actual error message first, don't guess.
- Fix incrementally — one error at a time, verify between fixes.
- Don't suppress warnings to make a build pass. Fix the underlying issue.
---
description: Security rules for secrets, auth, injection prevention, headers, and AI/LLM safety
alwaysApply: true
---
# Security
## Secrets Management
- NEVER hardcode secrets, API keys, tokens, or connection strings in code.
- Dev: User Secrets (`dotnet user-secrets`). Prod: Azure Key Vault.
- Frontend: NEVER put secrets in Angular/client-side code — backend proxies all external API calls.
- If a secret is exposed: rotate immediately, check Application Insights for exploitation.
## Input Validation & Injection
- All user input validated at system boundaries (FluentValidation / Angular reactive forms).
- SQL: EF Core only (auto-parameterized). Raw SQL: `FromSqlInterpolated` only — never string concatenation.
- XSS: Angular auto-escapes by default. Use `DomSanitizer` only when unavoidable, with a comment explaining why.
- CSRF protection enabled on all state-changing endpoints.
## Authentication & Authorization
- Auth required on all endpoints. Rate limiting on public endpoints.
- JWT: ValidateLifetime=true, ClockSkew=Zero, validate issuer + audience + signing key.
- CORS: explicit allowlist only (`CorsAllowedOrigins`), never wildcard in production.
## HTTP Security Headers
- X-Frame-Options: DENY
- X-Content-Type-Options: nosniff
- Content-Security-Policy: restrictive default
- Strict-Transport-Security: max-age=31536000; includeSubDomains
- Error responses: never leak stack traces, internal paths, or sensitive data.
## AI/LLM Security
- Validate and sanitize all LLM inputs and outputs — treat model output as untrusted.
- Content safety middleware on all agent endpoints.
- Tool permissions enforced via pipeline behavior — tools only accessible to authorized agents.
- Prompt injection defense: never embed raw user input directly into system prompts.
## Supply Chain
- Run `dotnet list package --vulnerable` and `npm audit` before adding new dependencies.
- Pin major versions. Review changelogs before upgrading.
## If Security Issue Found
1. STOP current work — security takes priority over all other tasks.
2. Fix CRITICAL issues before resuming other work.
3. Rotate any exposed secrets, audit logs for exploitation.
---
description: Testing conventions, bug fix workflow, TDD, mocking discipline, and test commands
alwaysApply: true
---
# Testing
## Bug Fix Workflow (MANDATORY)
When I report a bug, don't start by trying to fix it. Instead:
1. Write a test that reproduces the bug (prove it fails)
2. Have subagents try to fix the bug and prove it with a passing test
3. The fix isn't done until the test passes
This applies to all projects, always.
## Coverage: 80% minimum
Unit + Integration + E2E for critical flows.
## TDD (when requested)
RED (write failing test) → GREEN (minimal implementation) → REFACTOR (clean up, verify coverage)
## Test Naming
- C#: `MethodName_Scenario_ExpectedResult` (e.g., `Handle_InvalidRequest_ReturnsValidationFailure`)
- TypeScript/Angular: descriptive `it('should ...')` strings
- Python: `test_scenario_expected_result`
## Mocking Discipline
- Prefer real implementations over mocks. Use `WebApplicationFactory<Program>` + in-memory DB for integration tests.
- Only mock external services (HTTP clients, third-party APIs) and time (`TimeProvider`).
- Never mock the thing you're testing. Never mock value objects or DTOs.
## Patterns
- C#: xUnit, Arrange-Act-Assert, Moq (sparingly), `WebApplicationFactory<Program>` + in-memory DB for pipeline tests
- Angular: Jasmine/Karma, `HttpTestingController`, `afterEach(() => httpMock.verify())`
- Python: pytest, fixtures over setup methods, parametrize for variant cases
- E2E: Playwright with `data-testid` selectors
## Commands
- C#: `dotnet test`, `dotnet test --collect:"XPlat Code Coverage"`
- Angular: `ng test --code-coverage`, `ng test --watch=false --browsers=ChromeHeadless`
- Python: `pytest`, `pytest --cov`
- E2E: `npx playwright test`
Dashboard Creator
Create interactive HTML dashboards with KPI cards and charts.
When to Use
- "Create dashboard for [metrics]"
- "Show KPI visualization"
- "Generate performance dashboard"
- "Make analytics dashboard with charts"
Components
1. KPI Cards: metric name, value, change %, trend icon 2. Charts: bar/pie/line using SVG or CSS 3. Progress Bars: completion indicators 4. Data Tables: tabular data display
HTML Structure
<!DOCTYPE html>
<html>
<head>
<title>[Project] Dashboard</title>
<style>
body { font-family: system-ui; background: #f7fafc; }
.kpi-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.kpi-value { font-size: 36px; font-weight: bold; }
.trend-up { color: #48bb78; }
.trend-down { color: #e53e3e; }
</style>
</head>
<body>
<h1>[Dashboard Name]</h1>
<div class="grid">
<!-- KPI cards -->
<!-- Charts -->
<!-- Progress bars -->
</div>
</body>
</html>KPI Card Pattern
<div class="kpi-card">
<div class="kpi-label">Revenue</div>
<div class="kpi-value">$124K</div>
<div class="trend-up">↑ 12.5%</div>
</div>Chart Pattern (SVG Bar Chart)
<svg viewBox="0 0 400 300">
<rect x="50" y="100" width="40" height="150" fill="#4299e1"/>
<rect x="120" y="80" width="40" height="170" fill="#48bb78"/>
<!-- bars for each data point -->
</svg>Workflow
1. Extract metrics and data 2. Create KPI cards grid 3. Generate charts (bar/pie/line) as SVG 4. Add progress indicators 5. Write to [name]-dashboard.html
Use semantic colors: green (positive), red (negative), blue (neutral).
Demo Video Skill
Capture screenshots, record demo videos, and create optimized GIFs for GitHub project documentation.
Quick Reference
| Task | Tool | Requires |
|---|---|---|
| Check dependencies | check-deps.js | -- |
| Browser screenshot | screenshot-web.js | Playwright |
| Desktop/window screenshot | screenshot-desktop.ps1 | PowerShell |
| Browser video recording | record-web.js | Playwright |
| MP4 to GIF | to-gif.js | ffmpeg |
| PNGs to GIF slideshow | slideshow.js | ffmpeg |
---
Step 1: Check Dependencies
Ensure required tools are installed:
- Playwright: For web app capture. Install with
npx playwright install chromium. - ffmpeg: For GIF/video conversion. Install with
winget install Gyan.FFmpeg(Windows) orbrew install ffmpeg(macOS).
Degradation strategy:
- Playwright missing: Cannot capture web apps.
- ffmpeg missing: Can still take screenshots, but no GIF/video conversion.
- Both missing: Only desktop screenshots via PowerShell work.
Do NOT block on missing ffmpeg if the user only needs screenshots.
---
Step 2: Detect Project Type
Examine the project to determine capture method:
| Signal | Project Type | Method |
|---|---|---|
package.json with start/dev script, or angular.json, next.config.*, vite.config.* | Web app (local server) | Browser capture |
.html files in root or public/ | Static web | Browser capture (file://) |
.csproj with Microsoft.NET.Sdk.Web | .NET web app | Browser capture |
.exe, .ps1, or CLI tool | Desktop/CLI app | Desktop capture |
| No UI at all | Library/API | Screenshot of docs, tests, or terminal output |
Ask the user if detection is ambiguous.
---
Step 3: Choose Capture Method
| Goal | Method |
|---|---|
| Single web screenshot | Playwright screenshot |
| Full-page web screenshot | Playwright with --full-page |
| Desktop/window screenshot | PowerShell screen capture |
| Web interaction recording | Playwright video recording |
| MP4 to GIF | ffmpeg conversion |
| Multiple screenshots to GIF | ffmpeg slideshow |
---
Step 4: Plan the Demo
Before capturing, confirm with the user:
1. What to capture -- Which screens, features, or interactions? 2. Shot list -- Ordered list of captures needed. 3. Output format -- Screenshot (PNG), GIF, or video (MP4)? 4. Dark mode? -- Dark backgrounds compress better in GIFs.
Present the plan and wait for confirmation before proceeding.
---
Step 5: Capture
Web Screenshots
# Basic screenshot
npx playwright screenshot "http://localhost:3000" --output "./output/screenshot.png"
# Full page
npx playwright screenshot "http://localhost:3000" --output "./output/screenshot.png" --full-pageOptions: --full-page, --wait-for <selector>, --dark-mode
Desktop Screenshots (Windows PowerShell)
# Capture entire screen or specific window
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Screen]::PrimaryScreen | ForEach-Object {
$bitmap = New-Object System.Drawing.Bitmap($_.Bounds.Width, $_.Bounds.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($_.Bounds.Location, [System.Drawing.Point]::Empty, $_.Bounds.Size)
$bitmap.Save("./output/screenshot.png")
}Web Recording
Use Playwright to record browser interactions as MP4, then convert to GIF.
Supported actions: click, type, wait, scroll, navigate, hover.
---
Step 6: Post-Process
Convert MP4 to GIF
ffmpeg -i "./output/recording.mp4" -vf "fps=10,scale=640:-1" -gifflags +transdiff "./output/demo.gif"Auto-retry with reduced settings if over size limit:
- Pass 1: 640w, 10fps
- Pass 2: 480w, 8fps
- Pass 3: 320w, 6fps
Create Slideshow from Screenshots
ffmpeg -framerate 0.5 -pattern_type glob -i "./output/*.png" -vf "scale=640:-1" "./output/slideshow.gif"---
Step 7: Deliver
After capturing, provide the user with:
1. File locations -- List all generated files in output/. 2. README snippet -- Suggest markdown for their README:
## Demo

## Screenshots
| Feature | Preview |
|---------|---------|
| Dashboard |  |
| Settings |  |3. Gitignore reminder -- If output/ is not in .gitignore, suggest adding it (large binary files should not be committed). Recommend committing only the final optimized GIF/PNG.
---
Troubleshooting
| Problem | Solution |
|---|---|
| Playwright not found | Run npx playwright install chromium |
| ffmpeg not found | Run winget install Gyan.FFmpeg then restart terminal |
| Screenshot is blank/white | Increase wait time or use a wait-for selector |
| GIF too large for GitHub | Reduce size or use lower fps/width |
| Dark mode not applying | Site must respect prefers-color-scheme media query |
---
References
- GitHub GIF limits: <5MB for fast loading, <10MB max
- Recommended: 1280x720 for screenshots, 640px wide for GIFs, 10fps, 5-15s duration
DOCX Creation, Editing, and Analysis
Overview
Work with .docx files for creation, editing, and analysis. A .docx file is essentially a ZIP archive containing XML files and other resources that you can read or edit.
Workflow Decision Tree
Reading/Analyzing Content
Use "Text extraction" or "Raw XML access" sections below
Creating New Document
Use "Creating a new Word document" workflow
Editing Existing Document
- Your own document + simple changes: Use "Basic OOXML editing" workflow
- Someone else's document: Use "Redlining workflow" (recommended default)
- Legal, academic, business, or government docs: Use "Redlining workflow" (required)
Reading and Analyzing Content
Text Extraction
Convert the document to markdown using pandoc for excellent structure preservation:
# Convert document to markdown with tracked changes
pandoc --track-changes=all path-to-file.docx -o output.md
# Options: --track-changes=accept/reject/allRaw XML Access
Needed for: comments, complex formatting, document structure, embedded media, and metadata.
Unpacking a file
python ooxml/scripts/unpack.py <office_file> <output_directory>Key file structures
word/document.xml- Main document contentsword/comments.xml- Comments referenced in document.xmlword/media/- Embedded images and media files- Tracked changes use
<w:ins>(insertions) and<w:del>(deletions) tags
Creating a New Word Document
Use docx-js to create Word documents using JavaScript/TypeScript.
Workflow
1. Read the docx-js documentation for detailed syntax, critical formatting rules, and best practices 2. Create a JavaScript/TypeScript file using Document, Paragraph, TextRun components 3. Export as .docx using Packer.toBuffer()
Editing an Existing Word Document
Use the Document library (a Python library for OOXML manipulation).
Workflow
1. Read the ooxml documentation for the Document library API and XML patterns 2. Unpack the document: python ooxml/scripts/unpack.py <office_file> <output_directory> 3. Create and run a Python script using the Document library 4. Pack the final document: python ooxml/scripts/pack.py <input_directory> <office_file>
Redlining Workflow for Document Review
This workflow allows you to plan comprehensive tracked changes using markdown before implementing them in OOXML.
Batching Strategy: Group related changes into batches of 3-10 changes. Test each batch before moving to the next.
Principle: Minimal, Precise Edits Only mark text that actually changes. Repeating unchanged text makes edits harder to review. Break replacements into: [unchanged text] + [deletion] + [insertion] + [unchanged text].
Example - Changing "30 days" to "60 days" in a sentence:
# BAD - Replaces entire sentence
'<w:del><w:r><w:delText>The term is 30 days.</w:delText></w:r></w:del><w:ins><w:r><w:t>The term is 60 days.</w:t></w:r></w:ins>'
# GOOD - Only marks what changed
'<w:r w:rsidR="00AB12CD"><w:t>The term is </w:t></w:r><w:del><w:r><w:delText>30</w:delText></w:r></w:del><w:ins><w:r><w:t>60</w:t></w:r></w:ins><w:r w:rsidR="00AB12CD"><w:t> days.</w:t></w:r>'Tracked Changes Workflow
1. Get markdown representation: Convert document to markdown with tracked changes preserved:
pandoc --track-changes=all path-to-file.docx -o current.md2. Identify and group changes: Review the document and identify ALL changes needed, organizing them into logical batches.
Location methods (for finding changes in XML):
- Section/heading numbers
- Paragraph identifiers if numbered
- Grep patterns with unique surrounding text
- Document structure (e.g., "first paragraph", "signature block")
- DO NOT use markdown line numbers -- they don't map to XML structure
3. Read documentation and unpack:
- Read the ooxml documentation, especially "Document Library" and "Tracked Change Patterns" sections.
- Unpack the document:
python ooxml/scripts/unpack.py <file.docx> <dir>
4. Implement changes in batches: For each batch:
- Map text to XML: Grep for text in
word/document.xmlto verify how text is split across<w:r>elements. - Create and run script: Use
get_nodeto find nodes, implement changes, thendoc.save(). - Always grep
word/document.xmlimmediately before writing a script to get current line numbers.
5. Pack the document: python ooxml/scripts/pack.py unpacked reviewed-document.docx
6. Final verification:
pandoc --track-changes=all reviewed-document.docx -o verification.md
grep "original phrase" verification.md # Should NOT find it
grep "replacement phrase" verification.md # Should find itConverting Documents to Images
# Convert DOCX to PDF
soffice --headless --convert-to pdf document.docx
# Convert PDF pages to JPEG images
pdftoppm -jpeg -r 150 document.pdf page
# Creates page-1.jpg, page-2.jpg, etc.Code Style Guidelines
When generating code for DOCX operations: write concise code, avoid verbose variable names and redundant operations, avoid unnecessary print statements.
Dependencies
- pandoc: For text extraction
- docx:
npm install -g docx(for creating new documents) - LibreOffice: For PDF conversion
- Poppler: For pdftoppm (PDF to images)
- defusedxml:
pip install defusedxml(for secure XML parsing)
Excalidraw Diagram Generator
Generate Excalidraw-format diagrams from natural language descriptions. Creates visual representations of processes, systems, relationships, and ideas without manual drawing.
When to Use This Skill
Use when users request:
- "Create a diagram showing..."
- "Make a flowchart for..."
- "Visualize the process of..."
- "Draw the system architecture of..."
- "Generate a mind map about..."
- "Create an Excalidraw file for..."
- "Show the relationship between..."
- "Diagram the workflow of..."
Supported diagram types:
- Flowcharts: Sequential processes, workflows, decision trees
- Relationship Diagrams: Entity relationships, system components, dependencies
- Mind Maps: Concept hierarchies, brainstorming results, topic organization
- Architecture Diagrams: System design, module interactions, data flow
- Data Flow Diagrams (DFD): Data flow visualization, data transformation processes
- Business Flow (Swimlane): Cross-functional workflows, actor-based process flows
- Class Diagrams: Object-oriented design, class structures and relationships
- Sequence Diagrams: Object interactions over time, message flows
- ER Diagrams: Database entity relationships, data models
Prerequisites
- Clear description of what should be visualized
- Identification of key entities, steps, or concepts
- Understanding of relationships or flow between elements
Step-by-Step Workflow
Step 1: Understand the Request
Analyze the user's description to determine: 1. Diagram type (flowchart, relationship, mind map, architecture) 2. Key elements (entities, steps, concepts) 3. Relationships (flow, connections, hierarchy) 4. Complexity (number of elements)
Step 2: Choose the Appropriate Diagram Type
| User Intent | Diagram Type | Example Keywords |
|---|---|---|
| Process flow, steps, procedures | Flowchart | "workflow", "process", "steps", "procedure" |
| Connections, dependencies | Relationship Diagram | "relationship", "connections", "dependencies" |
| Concept hierarchy, brainstorming | Mind Map | "mind map", "concepts", "ideas", "breakdown" |
| System design, components | Architecture Diagram | "architecture", "system", "components", "modules" |
| Data flow, transformation | Data Flow Diagram (DFD) | "data flow", "data processing" |
| Cross-functional processes | Business Flow (Swimlane) | "business process", "swimlane", "actors" |
| Object-oriented design | Class Diagram | "class", "inheritance", "OOP" |
| Interaction sequences | Sequence Diagram | "sequence", "interaction", "messages" |
| Database design | ER Diagram | "database", "entity", "relationship", "data model" |
Step 3: Extract Structured Information
For Flowcharts:
- List of sequential steps
- Decision points (if any)
- Start and end points
For Relationship Diagrams:
- Entities/nodes (name + optional description)
- Relationships between entities (from -> to, with label)
For Mind Maps:
- Central topic
- Main branches (3-6 recommended)
- Sub-topics for each branch (optional)
For Data Flow Diagrams (DFD):
- Data sources and destinations (external entities)
- Processes (data transformations)
- Data stores (databases, files)
- Data flows (arrows showing data movement)
- Important: Do not represent process order, only data flow
For Business Flow (Swimlane):
- Actors/roles (departments, systems, people) as header columns
- Process lanes (vertical lanes under each actor)
- Process boxes (activities within each lane)
- Flow arrows (connecting process boxes, including cross-lane handoffs)
For Class Diagrams:
- Classes with names
- Attributes with visibility (+, -, #)
- Methods with visibility and parameters
- Relationships: inheritance, implementation, association, dependency, aggregation, composition
- Multiplicity notations (1, 0..1, 1.., )
For Sequence Diagrams:
- Objects/actors (arranged horizontally at top)
- Lifelines (vertical lines from each object)
- Messages (horizontal arrows between lifelines)
- Synchronous/asynchronous messages
- Return values (dashed arrows)
- Activation boxes
For ER Diagrams:
- Entities (rectangles with entity names)
- Attributes (listed inside entities)
- Primary keys (underlined or marked with PK)
- Foreign keys (marked with FK)
- Relationships and cardinality (1:1, 1:N, N:M)
Step 4: Generate the Excalidraw JSON
Create the .excalidraw file with appropriate elements:
Available element types:
rectangle: Boxes for entities, steps, conceptsellipse: Alternative shapes for emphasisdiamond: Decision pointsarrow: Directional connectionstext: Labels and annotations
Key properties to set:
- Position:
x,ycoordinates - Size:
width,height - Style:
strokeColor,backgroundColor,fillStyle - Font:
fontFamily: 5(Excalifont -- required for all text elements) - Text: Embedded text for labels
- Connections:
pointsarray for arrows
Step 5: Format the Output
Structure the complete Excalidraw file:
{
"type": "excalidraw",
"version": 2,
"source": "https://excalidraw.com",
"elements": [
// Array of diagram elements
],
"appState": {
"viewBackgroundColor": "#ffffff",
"gridSize": 20
},
"files": {}
}Step 6: Save and Provide Instructions
1. Save as <descriptive-name>.excalidraw 2. Inform user how to open:
- Visit https://excalidraw.com
- Click "Open" or drag-and-drop the file
- Or use Excalidraw VS Code extension
Best Practices
Element Count Guidelines
| Diagram Type | Recommended Count | Maximum |
|---|---|---|
| Flowchart steps | 3-10 | 15 |
| Relationship entities | 3-8 | 12 |
| Mind map branches | 4-6 | 8 |
| Mind map sub-topics per branch | 2-4 | 6 |
Layout Tips
1. Start positions: Center important elements, use consistent spacing 2. Spacing:
- Horizontal gap: 200-300px between elements
- Vertical gap: 100-150px between rows
3. Colors: Use consistent color scheme
- Primary elements: Light blue (
#a5d8ff) - Secondary elements: Light green (
#b2f2bb) - Important/Central: Yellow (
#ffd43b) - Alerts/Warnings: Light red (
#ffc9c9)
4. Text sizing: 16-24px for readability 5. Font: Always use fontFamily: 5 (Excalifont) 6. Arrow style: Straight arrows for simple flows, curved for complex relationships
Complexity Management
If user request has too many elements:
- Suggest breaking into multiple diagrams
- Focus on main elements first
- Offer to create detailed sub-diagrams
Icon Libraries (Optional Enhancement)
For specialized diagrams (e.g., AWS/GCP/Azure architecture), you can use pre-made icon libraries from Excalidraw.
Setup instructions: 1. Visit https://libraries.excalidraw.com/ 2. Search for the desired icon set and download the .excalidrawlib file 3. Place in a libraries/<icon-set-name>/ directory 4. Use a splitter script to extract individual icons
Using icons with Python scripts:
# Add icon to diagram at position with label
python scripts/add-icon-to-diagram.py diagram.excalidraw EC2 400 300 --label "Web Server"
# Add connecting arrows
python scripts/add-arrow.py diagram.excalidraw 300 250 500 300 --label "HTTPS"Fallback when no icons available:
- Use basic shapes (rectangles, ellipses, arrows)
- Apply color coding and text labels
- The diagram will still be functional and clear
Validation Checklist
Before delivering the diagram:
- [ ] All elements have unique IDs
- [ ] Coordinates prevent overlapping
- [ ] Text is readable (font size 16+)
- [ ] All text elements use
fontFamily: 5(Excalifont) - [ ] Arrows connect logically
- [ ] Colors follow consistent scheme
- [ ] File is valid JSON
- [ ] Element count is reasonable (<20 for clarity)
Output Summary Format
Always provide: 1. Complete .excalidraw JSON file 2. Summary of what was created 3. Element count 4. Instructions for opening/editing
Example:
Created: user-workflow.excalidraw
Type: Flowchart
Elements: 7 rectangles, 6 arrows, 1 title text
Total: 14 elements
To view:
1. Visit https://excalidraw.com
2. Drag and drop user-workflow.excalidraw
3. Or use File -> Open in Excalidraw VS Code extensionLimitations
- Complex curves are simplified to straight/basic curved lines
- Hand-drawn roughness is set to default (1)
- No embedded images support in auto-generation
- Maximum recommended elements: 20 per diagram
- No automatic collision detection (use spacing guidelines)
# Eval results may contain secrets from real config files.
# Never commit actual run output.
*
!.gitignore
!.gitkeep
Common Patterns
Privacy Tags
Wrap sensitive content in <private> tags to exclude from session memory logs. The observation hook only records file paths, not contents — use <private> for sensitive content in prompts.
Skeleton Projects
When implementing new functionality: search for battle-tested skeleton projects, evaluate with parallel agents, clone best match as foundation.