Opinionated Claude Code plugin for ultrawork, orchestration guardrails, and review gates.

version
0.14.0
GitHub stars
174

Install

/plugin install oh-my-claude@oh-my-claude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add TechDufus/oh-my-claude.

Contents

Discovered from source

Skills 12

Debugger Skill

Systematic debugging methodology for diagnosing failures and root cause analysis.

When to Apply This Guidance

  • 2+ failed fix attempts on the same issue
  • Debugging that's gone in circles
  • Complex system behavior you don't understand
  • Multi-system integration problems
  • Intermittent failures (Heisenbugs)

Structured Analysis Framework

Step 1: Restate the Problem

Before investigating, articulate:

  • What is the actual vs expected behavior?
  • What assumptions might be wrong?
  • What could cause the specific symptoms described?
  • Are there hidden dependencies or side effects?

Step 2: Generate Ranked Hypotheses

Always generate multiple hypotheses, ranked by likelihood:

Most Likely:

  • Evidence: What supports this theory?
  • Test: How to verify quickly?

Possible:

  • Evidence: What partially supports this?
  • Test: How to confirm or eliminate?

Unlikely but worth checking:

  • Evidence: Limited, but possible
  • Test: Quick check to rule out

Step 3: Systematic Verification

Test hypotheses in order. For each:

  1. State what you're testing
  2. Describe the expected outcome if hypothesis is correct
  3. Execute the test
  4. Document actual results
  5. Update hypothesis ranking based on findings

Reasoning Principles

  1. Challenge assumptions - The "obvious" cause is often wrong after 2+ failures
  2. Follow the data - What do logs/errors actually say vs what's assumed?
  3. Consider timing - Race conditions, async issues, initialization order
  4. Check boundaries - Module interfaces, API contracts, type conversions
  5. Question the environment - Config, dependencies, network, state

Decision Framework

When choosing between approaches:

FactorWeightConsiderations
CorrectnessCriticalDoes it actually solve the problem?
SimplicityHighPrefer boring solutions over clever ones
LeverageHighUse existing patterns/libraries/code
Developer ExperienceMediumHow hard is it to debug/maintain?
PerformanceLow**Unless performance IS the problem

Effort Estimation

Tag recommendations by effort:

TagMeaningExample
[Quick]<30 minAdd logging, check config
[Short]30min-2hrRefactor function, add test
[Medium]2hr-1dayNew component, integration
[Large]>1 dayArchitecture change

Common Failure Patterns

PatternSignalInvestigation Focus
Fix-break cycleEach fix causes new problemRoot cause analysis - treating symptoms not cause
Confusion"I don't understand why X happens"Add logging, trace execution path
Tradeoff paralysisMultiple valid approachesUse decision framework above
Integration hellSystem A + B don't work togetherInterface contracts, data formats
HeisenbugWorks sometimes, fails randomlyTiming, state, race conditions

Traps to Avoid

  • Premature fixing - Understand before changing
  • Single hypothesis - Always consider alternatives
  • Assuming correctness - Verify each component independently
  • Ignoring evidence - If data contradicts theory, update theory
  • Scope creep - Fix the bug, not everything around it

Output Template

When debugging, structure findings as:

## Problem Understanding
{Restate in own words. Challenge framing if wrong.}

## Hypotheses (Ranked)
1. Most Likely: {hypothesis} - Evidence: {support} - Test: {verification}
2. Possible: {hypothesis} - Evidence: {support} - Test: {verification}
3. Unlikely: {hypothesis} - Evidence: {limited} - Test: {quick check}

## Recommended Approach
{Specific next steps. Be prescriptive.}

## Traps to Avoid
{What NOT to do for this specific problem.}

Git Commit Validator

This skill MUST be invoked whenever you are about to create a git commit. It handles the complete workflow and enforces commit message standards.

When This Skill Activates

Auto-invoke this skill when the user implies code should be committed:

CategoryTrigger Phrases
Explicit commit"commit", "make a commit", "commit this"
Ship intent"ship it", "send it"
Finalization"wrap it up", "finalize this", "we're done", "that's it"
After implementationWhen you complete work and there are uncommitted changes

Key insight: If the user's intent results in git commit being run, this skill MUST be used first.

Do NOT run git commit without this skill.

Complete Commit Workflow

Step 1: Gather Context

git status                    # See what's changed
git diff HEAD                 # See all changes (staged + unstaged)
git log --oneline -5          # Recent commit style reference

Step 1.5: Handle No Changes

If git status --porcelain returns empty AND nothing is staged:

  • Do not attempt to commit - there's nothing to commit
  • Inform the user: "No changes to commit"
  • Exit the workflow

This prevents errors from running git commit with nothing staged.

Step 2: Stage Changes

Default behavior - stage all changes:

git add -A

If user specifies --staged - skip staging, use only what's already staged.

If user gives instructions - follow them:

  • "ignore the docs" → don't stage doc files
  • "only the src folder" → stage selectively

Step 3: Analyze and Generate Message

Based on the diff, determine:

  1. Type: feat, fix, docs, refactor, test, chore, perf, ci, build, style, revert
  2. Scope (optional): module or area affected
  3. Description: concise, imperative mood, lowercase
  4. Body: see decision matrix below

Message Format:

<type>[optional scope]: <description>

[body - required for non-trivial changes]

[optional footer - breaking changes, issue refs]

Commit Body Decision Matrix

The body is NOT optional for most real work. Use this matrix:

Change TypeBody Required?Body Content
Typo fix, single-line changeNoSubject is sufficient
Config tweak, version bumpNoSubject is sufficient
Bug fixYESWhat caused it, how you fixed it
New featureYESWhat it does, why it's needed, key design choices
RefactorYESWhat changed structurally, why this approach
Multiple files changedYESWhat each area of change accomplishes
Breaking changeYESWhat breaks, migration path
Performance improvementYESWhat was slow, what's faster, by how much

Body Quality Standards

Good body content includes:

  • Context: Why this change is needed (the problem)
  • Approach: How you solved it (key decisions)
  • Impact: What this enables or fixes
  • Caveats: Limitations, follow-up work, edge cases

Use bullet points when listing multiple changes:

- Add validation for email format
- Refactor user service to async
- Update tests for new behavior

Wrap at 72 characters - hard requirement for git tooling compatibility.

Sizing Your Commit Message

Diff SizeExpected Message
1-10 linesSubject only (if truly trivial)
10-50 linesSubject + 1-2 sentence body
50-200 linesSubject + paragraph or bullets
200+ linesSubject + detailed body with sections

When in doubt, write more. A detailed commit message is a gift to future developers (including yourself).

Step 4: Validation (Automatic)

Validation runs automatically when you execute git commit. The commit_quality_enforcer hook intercepts the command and validates:

  1. Subject line <= 50 chars
  2. Body lines <= 72 chars (if body present)
  3. Format check - Must match conventional commit format: <type>[scope]: <description>
  4. No AI attribution - Rejects "generated with", "co-authored-by.*claude", "ai-generated"
  5. Body quality - Requires appropriate detail based on diff size

If validation fails, the commit is blocked with a clear error message. Fix the issues and retry.

Step 5: Commit

Use HEREDOC for proper formatting:

git commit -m "$(cat <<'EOF'
type: description here
EOF
)"

Validation Rules

Subject Line (Required)

  • Max 50 characters
  • Format: <type>[scope]: <description>
  • Type: lowercase (feat, fix, docs, style, refactor, test, chore, perf, ci, build, revert)
  • Description: lowercase start, no period at end, imperative mood

Body Lines (Required for non-trivial changes)

  • Max 72 characters per line
  • Blank line between subject and body
  • Explain "why" not just "what"
  • See decision matrix above for when body is required

Forbidden Content

  • NO AI attribution ("Generated with Claude", "Created by AI")
  • NO AI co-authors ("Co-authored-by: Claude")
  • NO branding phrases

Type Reference

TypeUse For
featNew feature or capability
fixBug fix
docsDocumentation only
refactorCode restructuring (no behavior change)
perfPerformance improvement
testTest additions/fixes
choreMaintenance, deps
ciCI/CD changes
buildBuild system changes
styleFormatting (no logic change)
revertReverting previous commit

Examples

Minimal (only for truly trivial changes)

docs: fix typo in readme
chore: bump lodash to 4.17.21

Standard (most commits should look like this)

fix(api): resolve timeout on large file uploads

Requests over 10MB were hitting the default 30s timeout.
Increased timeout to 5 minutes for upload endpoints and added
progress tracking to prevent connection drops.
feat(auth): add password reset via email

Users can now request a password reset link sent to their
registered email. Link expires after 1 hour.

- Add /auth/forgot-password endpoint
- Add /auth/reset-password endpoint with token validation
- Integrate SendGrid for transactional emails
- Add rate limiting (3 requests per hour per email)

Detailed (for large or complex changes)

refactor(database): migrate from callbacks to async/await

The callback-based database layer was causing pyramid-of-doom
issues and making error handling inconsistent across services.

Changes:
- Convert all db methods to return Promises
- Update 47 call sites across 12 service files
- Add connection pool management with proper cleanup
- Standardize error types (DbConnectionError, DbQueryError)

This unblocks the upcoming transaction support work.
feat(hooks): add pre-delegation context injection

Problem: Agents were receiving prompts without project context,
leading to inconsistent code style and missed conventions.

Solution: SessionStart hook now injects a delegation template
into Claude's context that gets included with every Agent() call.

Template includes:
- 7 sections covering task, context, expected output
- MUST DO / MUST NOT constraints
- Verification checklist

This standardizes agent output quality across all delegations.

Why No AI Attribution?

Commit messages reflect intent and ownership of the change. AI attribution:

  • Clutters git history
  • Dilutes accountability
  • Adds no useful information

The human owns the commit. The tool is irrelevant.


Note: This skill handles COMMIT only. Push must be requested separately.

Init Deep Skill

Create a minimal root CLAUDE.md with nested CLAUDE.md files throughout the repository for true progressive disclosure.

Key Insight

Claude automatically loads CLAUDE.md from any directory it reads. Instead of centralizing documentation in .claude/docs/, place CLAUDE.md files directly in relevant directories. When Claude reads src/api/users.ts, it also loads src/api/CLAUDE.md - contextual guidance exactly when needed.

Closest Wins: When multiple CLAUDE.md files apply, the one closest to the file being edited takes precedence. A rule in src/api/CLAUDE.md overrides the same topic in root CLAUDE.md.

When This Skill Activates

CategoryTrigger Phrases
Initialize/init-deep, deep init, initialize deeply, setup claude deeply
Migraterefactor claude.md, migrate claude.md, restructure claude
Structurenested claude, progressive disclosure, contextual claude

CLI Variants

/init-deep              # Update: modify existing + create new where needed
/init-deep --fresh      # Delete all CLAUDE.md files, regenerate from scratch
/init-deep --max-depth=2 # Limit nesting depth (default: unlimited)
FlagBehavior
(none)Additive - creates missing, preserves existing
--freshDestructive - deletes all CLAUDE.md, starts clean
--max-depth=NLimits nested CLAUDE.md to N levels deep

Philosophy: Instruction Budget

Claude has ~150-200 instruction capacity before diminishing returns. A bloated root CLAUDE.md means wasted context on every interaction.

Solution: Minimal root + nested CLAUDE.md files that load only when relevant directories are accessed.

Size Limits (Strict)

FileLinesStatus
Root CLAUDE.md50-150Optimal range
Root CLAUDE.md150+Needs refactoring
Nested CLAUDE.md30-80Optimal range
Nested CLAUDE.md80+Too verbose

Telegraphic style required. No verbose explanations. Each line must carry weight.

Deduplication Rules

Child CLAUDE.md files NEVER repeat parent content:

  • If root says "use TypeScript" - children don't repeat it
  • If root defines import order - children inherit it
  • Child files add domain-specific rules only

Review Phase Requirement: Before finalizing, scan all generated CLAUDE.md files for duplicated guidance. Remove duplicates from children, keep in nearest common ancestor.


Directory Scoring System

Not every directory needs a CLAUDE.md. Use weighted scoring to decide.

Scoring Formula

Score = (file_count * 3) + (reference_centrality * 3) + (symbol_density * 1) + (export_count * 1)
FactorWeightHow to Measure
File count3xNumber of files in directory
Reference centrality3xHow many imports/exports reference this dir
Symbol density1xFunctions, classes, types defined
Export count1xPublic API surface

Score Thresholds

ScoreAction
>15Definitely gets CLAUDE.md
8-15Only if distinct domain (tests, api, components)
<8Parent CLAUDE.md covers it

Quick Heuristics

When scoring isn't practical, use these rules:

DirectoryCreate CLAUDE.md?Reason
tests/YESTesting patterns are domain-specific
src/components/YESComponent patterns are specialized
src/api/YESAPI design patterns are critical
src/hooks/MAYBEIf project has custom hooks
src/utils/MAYBEIf utility patterns are non-obvious
src/services/MAYBEIf services have specific patterns
src/MAYBEFor general coding conventions
scripts/RARELYOnly if complex build system
node_modules/NEVERNot your code
dist/NEVERGenerated code

Two Operating Modes

Mode 1: Fresh Project (No CLAUDE.md)

Create minimal root + nested structure from scratch.

Mode 2: Existing CLAUDE.md

Analyze, categorize, and migrate content to nested CLAUDE.md files.


Workflow

Phase 1: Discovery

Goal: Understand current state and scope.

Actions:

  1. Check if root CLAUDE.md exists
  2. Scan for common directories that should have nested CLAUDE.md
  3. Check for existing nested CLAUDE.md files
  4. Detect if .claude/docs/ exists (old pattern to migrate)
  5. Calculate directory scores for prioritization

Dynamic Agent Scaling:

ConditionAction
Files >100Spawn additional Explore agents
Depth >=4Increase exploration scope
Multiple languagesSpawn language-specific analysis

Concurrent Execution: Launch all exploration agents in parallel (one message, multiple Task calls). Do not wait for one to finish before starting others.

Directory Detection Patterns:

src/           # Source code root
tests/         # Test files
test/          # Alternative test directory
lib/           # Library code
api/           # API layer (may be under src/)
components/    # UI components
hooks/         # React/custom hooks
utils/         # Utility functions
services/      # Service layer
scripts/       # Build/dev scripts
packages/      # Monorepo packages
apps/          # Monorepo apps

Nested directory patterns (check inside src/):

src/api/
src/components/
src/hooks/
src/utils/
src/services/
src/lib/
src/routes/
src/pages/
src/stores/
src/models/

Detection Script:

# Find directories that should have CLAUDE.md
for dir in tests test src lib api components hooks utils services scripts packages apps; do
  if [ -d "$dir" ]; then
    echo "FOUND: $dir/"
  fi
done

# Check src/ subdirectories
if [ -d "src" ]; then
  for subdir in api components hooks utils services lib routes pages stores models; do
    if [ -d "src/$subdir" ]; then
      echo "FOUND: src/$subdir/"
    fi
  done
fi

Phase 2: Interview

Goal: Gather essential project info.

For Fresh Projects, Ask:

Question 1: Project Description

What does this project do? (One sentence)

Example: "A CLI tool for managing Kubernetes deployments"

Question 2: Package Manager

Which package manager does this project use?

Options:
- npm (default, will not be documented)
- pnpm
- yarn
- bun
- none (not a JS/TS project)

Question 3: Non-Standard Commands

Any build, test, or lint commands that differ from standard?

Leave blank if using standard commands (npm test, npm run build).
Only specify if different, e.g., "pytest -v" or "make release"

Question 4: Nested CLAUDE.md Selection

I detected these directories. Which should have their own CLAUDE.md?

Detected:
- [x] tests/
- [x] src/components/
- [x] src/api/
- [ ] src/utils/
- [ ] scripts/

Select all that would benefit from contextual guidance.
(Default: tests/ and any domain-specific src/ directories)

For Existing CLAUDE.md Migration, Ask:

Found existing CLAUDE.md ({N} lines). Options:

1. Analyze and migrate - Extract content to nested CLAUDE.md files
2. Replace - Create fresh minimal structure (backup original)
3. Cancel - Keep existing structure

Phase 3: Analysis (Existing CLAUDE.md Only)

Goal: Categorize existing content for migration.

Metrics to Calculate:

MetricHowThreshold
Line CountTotal non-empty lines>150 = needs migration
Instruction CountCount MUST/NEVER/ALWAYS/should>30 = instruction overload
Hardcoded PathsRegex for file paths>10 = staleness risk
SectionsCount ## headers>8 = fragmented

Content Categorization:

Map existing content to potential nested locations:

Content TypeDestination
Project description, tech stackRoot CLAUDE.md
Package manager, build commandsRoot CLAUDE.md
Task-to-location mappingRoot CLAUDE.md
Agent workflow guidanceRoot CLAUDE.md
Testing patterns, mocking, coveragetests/CLAUDE.md
Component patterns, naming, propssrc/components/CLAUDE.md
API design, endpoints, error handlingsrc/api/CLAUDE.md
Hook patterns, naming, dependenciessrc/hooks/CLAUDE.md
Utility patterns, when to usesrc/utils/CLAUDE.md
Service patterns, external integrationssrc/services/CLAUDE.md
Coding conventions (general)Root or src/CLAUDE.md

Analysis Output Template:

## CLAUDE.md Analysis

### Metrics
| Metric | Value | Status |
|--------|-------|--------|
| Total Lines | 245 | MIGRATE |
| Instructions | 52 | HIGH |
| Hardcoded Paths | 18 | WARNING |

### Content Migration Plan
| Lines | Content | Destination |
|-------|---------|-------------|
| 1-15 | Project description | Root CLAUDE.md |
| 20-45 | Testing patterns | tests/CLAUDE.md |
| 50-95 | Component conventions | src/components/CLAUDE.md |
| 100-140 | API design patterns | src/api/CLAUDE.md |
| 145-180 | General coding style | src/CLAUDE.md |
| 185-245 | Outdated/stale content | REMOVE (with approval) |

Phase 4: Generation

Goal: Create minimal root + nested CLAUDE.md files.

Parallel Generation: When creating multiple nested CLAUDE.md files, generate them in parallel (multiple Write calls in one message).

Root CLAUDE.md Template (50-100 lines target)
# {Project Name}

{One-sentence description}

## Development

{Package manager line - ONLY if not npm}

{Non-standard commands - ONLY if provided}

## Where to Look

| Task | Location |
|------|----------|
| Add new API endpoint | src/api/ |
| Add UI component | src/components/ |
| Add utility function | src/utils/ |
| Write tests | tests/ |
| Add service integration | src/services/ |
| Modify build/deploy | scripts/ |

## Agent Workflow

Explore finds -> Librarian reads -> You plan -> Worker implements -> Validator checks

When delegating to agents:
- Use positive constraints ("ensure X") not negative ("don't do Y")
- Include context, expected output, acceptance criteria
- Launch independent tasks in parallel

## Guidance

Context-specific guidance lives in nested CLAUDE.md files throughout the repo.
These load automatically when you work in those directories.
Closest CLAUDE.md to the file being edited takes precedence.

Conditional Rules:

  • Omit "Package manager" if npm
  • Omit "Development" section if no non-standard info
  • Customize "Where to Look" table based on actual project structure
  • Never include coding conventions (put in src/CLAUDE.md or nested)
Nested CLAUDE.md Templates

Each nested file: 30-80 lines max. Telegraphic style. Domain-specific anti-patterns required.


tests/CLAUDE.md Template (30-50 lines):

# Testing

## Framework

{e.g., Jest, Vitest, pytest, Go testing}

## Patterns

- Test files: `*.test.ts` or `*.spec.ts`
- Describe blocks mirror module structure
- One assertion per test when practical

## Running Tests

```bash
{test command}

Mocking

  • Prefer real implementations over mocks
  • Mock only: network, time, randomness, file system

Coverage

Focus on behavior, not percentage. Critical paths need thorough coverage.

Anti-Patterns

  • Don't mock what you can test directly
  • Don't test implementation details
  • Don't share mutable state between tests
  • Don't write tests that pass when code is broken

---

**src/components/CLAUDE.md Template (30-50 lines):**

```markdown
# Components

## Structure

ComponentName/ index.ts # Re-export ComponentName.tsx # Implementation ComponentName.test.tsx


## Naming

- Components: PascalCase
- Props interface: `{ComponentName}Props`
- Files match component name

## Patterns

- Prefer composition over inheritance
- Extract hooks for reusable logic
- Props over context for explicit dependencies

## Exports

{Named exports / default exports preference}

## Anti-Patterns

- Don't use inline styles when CSS modules exist
- Don't prop-drill beyond 2 levels - use context
- Don't mix data fetching with presentation
- Don't create god components (>200 lines)

src/api/CLAUDE.md Template (30-50 lines):

# API Layer

## Design

- RESTful endpoints / GraphQL / tRPC
- Consistent error response format
- Request validation at boundary

## Patterns

- Controllers handle HTTP concerns only
- Business logic lives in services
- Validate input, sanitize output

## Error Handling

{error response format example}


## Authentication

{auth pattern if applicable}

## Anti-Patterns

- Don't expose internal errors to clients
- Don't skip input validation
- Don't leak sensitive data in responses
- Don't mix auth logic with business logic

src/hooks/CLAUDE.md Template (30-50 lines):

# Hooks

## Naming

- Prefix with `use`: `useAuth`, `useForm`, `useFetch`
- Name describes the capability, not implementation

## Patterns

- Single responsibility per hook
- Return stable references (useMemo, useCallback)
- Handle cleanup in useEffect

## Testing

- Test hooks via @testing-library/react-hooks
- Test state transitions, not implementation

## Common Hooks

{list project-specific hooks if established}

## Anti-Patterns

- Don't call hooks conditionally
- Don't create hooks with side effects on mount without cleanup
- Don't return unstable references
- Don't nest hooks more than 2 levels deep

src/utils/CLAUDE.md Template (30-50 lines):

# Utilities

## When to Create

Create a utility when:
- Logic is used in 3+ places
- Function is pure (no side effects)
- Behavior is well-defined and testable

## Patterns

- Pure functions preferred
- No dependencies on external state
- Comprehensive input validation
- Clear, descriptive names

## Naming

- Functions: camelCase, verb-first (`formatDate`, `parseInput`)
- Files: kebab-case or camelCase (match project convention)

## Testing

Every utility function needs tests. They're isolated and easy to test.

## Anti-Patterns

- Don't create utils for single-use logic
- Don't add side effects to pure functions
- Don't create "misc" or "helpers" grab-bags
- Don't depend on global state

src/services/CLAUDE.md Template (30-50 lines):

# Services

## Purpose

Services encapsulate external integrations and complex business logic.

## Patterns

- One service per external dependency
- Services are injectable/mockable
- Handle retries, timeouts, circuit breaking

## Structure

services/ userService.ts authService.ts emailService.ts


## Error Handling

- Wrap external errors in domain-specific errors
- Log at service boundary
- Never expose internal details to callers

## Anti-Patterns

- Don't call services from other services directly - use orchestrator
- Don't mix HTTP/DB concerns in same service
- Don't retry without backoff
- Don't swallow errors silently

src/CLAUDE.md Template (30-50 lines):

# Source Code

## Style

- {indent style}
- {semicolons yes/no}
- {quote style}

## Imports

```typescript
// 1. External packages
// 2. Internal aliases (@/)
// 3. Relative imports
// 4. Types (import type)

Naming

  • Files: {convention}
  • Functions: camelCase
  • Classes: PascalCase
  • Constants: SCREAMING_SNAKE

Patterns

  • Prefer early returns
  • Explicit over implicit
  • Composition over inheritance

Anti-Patterns

  • Don't use any - use unknown and narrow
  • Don't nest callbacks >2 levels
  • Don't mutate function arguments
  • Don't use magic numbers without constants

---

**scripts/CLAUDE.md Template (30-50 lines):**

```markdown
# Scripts

## Purpose

Build, deployment, and development automation scripts.

## Conventions

- Scripts are executable: `chmod +x script.sh`
- Include usage comment at top
- Exit codes: 0 success, 1 error
- Use `set -euo pipefail` for bash scripts

## Running

```bash
./scripts/{script-name}.sh
# or
npm run {script-name}

Adding New Scripts

  1. Create in scripts/ directory
  2. Add npm script alias if frequently used
  3. Document purpose in script header

Anti-Patterns

  • Don't hardcode paths - use variables
  • Don't skip error handling
  • Don't assume dependencies exist - check first
  • Don't write scripts without idempotency

---

### Phase 5: Execution

**For Fresh Projects:**

1. Create root CLAUDE.md
2. Create nested CLAUDE.md files in detected/selected directories (parallel writes)
3. Report created files

**For Migration:**

1. Create backup: `cp CLAUDE.md CLAUDE.md.backup`
2. Create nested CLAUDE.md files with migrated content
3. Rewrite root CLAUDE.md to minimal version
4. If `.claude/docs/` exists, offer to migrate or remove
5. Present before/after comparison

**For --fresh Flag:**

1. Find all existing CLAUDE.md files: `find . -name "CLAUDE.md" -type f`
2. Delete all found CLAUDE.md files
3. Run fresh project workflow

**Deduplication Check (Required):**

Before finalizing, review all generated files:
1. List all rules in root CLAUDE.md
2. Check each nested file for duplicates
3. Remove any duplicated guidance from children
4. Only domain-specific additions remain in nested files

**Before/After Report:**

```markdown
## Migration Complete

### Before
- Root CLAUDE.md: 245 lines
- Nested CLAUDE.md: 0 files
- .claude/docs/: 3 files

### After
- Root CLAUDE.md: 85 lines (65% reduction)
- Nested CLAUDE.md: 4 files
  - tests/CLAUDE.md (35 lines)
  - src/components/CLAUDE.md (42 lines)
  - src/api/CLAUDE.md (38 lines)
  - src/CLAUDE.md (30 lines)

### Backup
Original preserved at CLAUDE.md.backup

### Benefit
Root context cost reduced from 245 to 85 lines.
Domain guidance loads only when working in those directories.

Behavior Rules

MUST DO

  • Detect existing CLAUDE.md before creating
  • Ask before overwriting any existing CLAUDE.md files
  • Create backup before modifying existing root CLAUDE.md
  • Keep root CLAUDE.md 50-150 lines
  • Keep nested CLAUDE.md files 30-80 lines each
  • Include domain-specific anti-patterns in each nested file
  • Run deduplication check before finalizing
  • Use parallel Task calls for exploration
  • Use parallel Write calls for generation

MUST NOT

  • Document hardcoded file paths (they go stale)
  • Include standard commands (npm test, npm run build)
  • Reference .claude/docs/ (old pattern)
  • Create overly comprehensive documentation
  • Create nested CLAUDE.md in directories that don't benefit
  • Duplicate parent guidance in child files
  • Execute agents sequentially when parallel is possible

SHOULD DO

  • Explain the auto-loading behavior
  • Explain "closest wins" precedence
  • Suggest which directories would benefit from nested CLAUDE.md
  • Offer to migrate .claude/docs/ content if it exists
  • Provide line counts in final report
  • Use scoring system for borderline directories

Content Location Decision

Content TypeLocation
Project purposeRoot
Package managerRoot
Non-standard commandsRoot
Where-to-look tableRoot
Agent workflow guidanceRoot
Testing philosophytests/CLAUDE.md
Component patternssrc/components/CLAUDE.md
API conventionssrc/api/CLAUDE.md
General code stylesrc/CLAUDE.md
Import orderingsrc/CLAUDE.md
Naming conventionssrc/CLAUDE.md or domain-specific

Error Handling

Directory Doesn't Exist

If selected directory doesn't exist:

  1. Ask: "Directory {dir} doesn't exist. Create it with CLAUDE.md, or skip?"
  2. Options: Create directory, Skip

Existing Nested CLAUDE.md

If nested CLAUDE.md already exists:

  1. Read current content
  2. Ask: "Found existing {dir}/CLAUDE.md. Merge, replace, or skip?"
  3. Options: Merge (append new patterns), Replace (backup first), Skip

Permission Denied

If cannot write files:

  1. Output generated content to chat
  2. Say: "Could not write files. Here's the content to add manually:"

Post-Generation Message

After creating files:

Created nested CLAUDE.md structure:

Root:
  - CLAUDE.md ({N} lines)

Nested:
  - tests/CLAUDE.md ({N} lines) - Testing patterns
  - src/components/CLAUDE.md ({N} lines) - Component patterns
  - src/api/CLAUDE.md ({N} lines) - API patterns

How it works:
Claude automatically loads CLAUDE.md from any directory it reads.
When you work in src/api/, the API patterns load automatically.
Closest file to your edit takes precedence ("closest wins").

Next steps:
1. Review each CLAUDE.md and customize for your project
2. Add patterns as they emerge during development
3. Keep files focused and minimal (30-80 lines nested, 50-150 root)

oh-my-claude

Intelligent automation with orchestration guardrails and specialized agents.

Context Protection (ALWAYS ON)

Your context window is for REASONING, not storage.

Protect your context. Delegate aggressively. Subagent context is free. When you dump a large file into context, that's less capacity for reasoning.

Communication Style

Start Immediately

  • No preamble ("I'll start by...", "Let me...", "I'm going to...")
  • No acknowledgments ("Sure!", "Great idea!", "I'm on it!")
  • Just start working. Use todos for progress tracking.

No Unnecessary Questions

When the user gives clear instructions:

  • "fix it" → fix it, don't ask "want me to fix it?"
  • "ship it" → commit it, don't ask "should I commit?"
  • "do X" → do X, don't ask "would you like me to do X?"

Only ask when:

  • Genuinely ambiguous with 2x+ effort difference between interpretations
  • Missing critical info you cannot infer from context
  • About to do something destructive user didn't explicitly request

No Status Summaries

Don't narrate your actions:

  • "First I'll read the file, then I'll..." → just read the file
  • "I've completed the task..." → just show the result
  • "Here's what I did..." → only if user asks

Answer Length

Match your response length to the task:

  • Simple question → short answer
  • Complex implementation → detailed but not verbose
  • Error occurred → state error + solution, not apology

Specialized Agents

All agents use model: inherit - same model as your session.

Model Inheritance (CRITICAL)

NEVER pass model: "haiku" or model: "sonnet" when spawning agents.

Always omit the model parameter or use model: "inherit". The Agent tool's default description mentions "prefer haiku for quick tasks" - IGNORE THIS. This plugin overrides that guidance. The user pays for their model tier - use it.

Correct: Agent(subagent_type="oh-my-claude:critic", prompt="...") WRONG: Agent(subagent_type="oh-my-claude:critic", model="haiku", prompt="...")

AgentJobWhen
advisorANALYZEPre-planning gap analysis, hidden requirements, scope risks
risk-assessorASSESSProactive change-risk pass during planning and PR review (functional, security, compatibility, performance, operational)
criticREVIEWReview plans critically BEFORE execution
code-reviewerREVIEWReview implementation AFTER code is written, before merge
validatorCHECKTests, linters, verification
librarianREADFiles >500 lines, summarize, extract, git analysis
security-auditorAUDITSecurity-focused code review: OWASP, secrets, injection, dependency CVEs

Usage: Agent(subagent_type="oh-my-claude:critic", prompt="Review this migration plan")

More examples:

  • Agent(subagent_type="oh-my-claude:advisor", prompt="Analyze scope risks for this refactor")
  • Agent(subagent_type="oh-my-claude:risk-assessor", prompt="Assess pre-implementation risk for this migration plan")
  • Agent(subagent_type="oh-my-claude:code-reviewer", prompt="Review the auth implementation")
  • Agent(subagent_type="oh-my-claude:validator", prompt="Run tests and verify the changes")
  • Agent(subagent_type="oh-my-claude:librarian", prompt="Summarize the auth module")
  • Agent(subagent_type="oh-my-claude:security-auditor", prompt="Audit the auth module for security vulnerabilities")

Claude Code renamed Task(...) to Agent(...) in v2.1.63. Use Agent(...) in new prompts. TaskCreate/TaskUpdate/TaskList/TaskGet stay the same.

Agent Disambiguation (Planning + Review Agents)

AgentReviewsWhenOutput
risk-assessorChange risk (plan or diff)Default for non-trivial planning; optional on PR reviewIntent summary + risk factors + 1-10 risk level + mitigations + recommendation
criticPlans (before execution)After Plan agent, before implementationAPPROVED / NEEDS_REVISION / REJECTED
code-reviewerImplementation (after execution)After code is written, before mergeStrengths + Issues (Critical/Important/Minor)
security-auditorSecurity posture (on demand)When deeper security analysis is needed beyond code-reviewerFindings (Critical/Important/Minor) + Security Posture verdict
validatorTechnical correctnessBefore declaring work completeVERDICT: PASS / FAIL with test/lint results

Flow: Plan → advisor scans gaps → risk-assessor evaluates change risk → critic reviews plan → implement → code-reviewer reviews → validator runs checks → done

Built-in Agents (Claude Code)

Use Claude Code's native agents for common tasks:

AgentJobWhen
ExploreFINDLocate files, definitions (use thoroughness: quick/medium/very thorough)
PlanPLANComplex tasks needing decomposition
general-purposeBUILDImplementation tasks

Usage: Agent(subagent_type="Explore", prompt="Find auth files", thoroughness="medium")

More examples:

  • Agent(subagent_type="Plan", prompt="Design the migration strategy")
  • Agent(subagent_type="general-purpose", prompt="Implement the UserAuth class")

Task System (Coordination Layer)

The Task system is your scratchpad for orchestrating multi-agent work.

Use TaskCreate/TaskUpdate/TaskList/TaskGet to:

  • Track progress on multi-step work
  • Model dependencies between tasks
  • Enable agent self-discovery via owner field
  • Persist state across parallel delegations

Task tools are built-in to Claude Code (TaskCreate, TaskUpdate, TaskList, TaskGet).

Quick Reference

# Create with metadata
TaskCreate(subject="Find auth files", description="...", metadata={"priority": "high"})

# Dependencies: addBlockedBy (I wait) vs addBlocks (others wait for me)
TaskUpdate(taskId="2", addBlockedBy=["1"])

# Agent self-discovery via owner
TaskUpdate(taskId="1", owner="explore-1")
Agent(subagent_type="Explore", prompt="Find auth-related files...")

Task System: Tracking vs Execution

Key distinction: Agent() = spawn agent NOW. TaskCreate() = track work for later.

# TRACKING: Create items to track progress
TaskCreate(subject="Implement auth", description="Add JWT middleware to API routes")
TaskCreate(subject="Write tests", description="Unit tests for auth middleware")
TaskUpdate(taskId="2", addBlockedBy=["1"])  # Tests blocked by implementation

# EXECUTION: Spawn agents to do work (parallel when independent)
Agent(subagent_type="general-purpose", prompt="Implement JWT middleware...")
Agent(subagent_type="oh-my-claude:validator", prompt="Run auth tests...")

# UPDATE: Mark complete after verification
TaskUpdate(taskId="1", status="completed")

Parallelization: Launch multiple Agent() calls in ONE message for parallel execution.

Escape hatch: Add [NO-DELEGATE] for tasks main agent handles directly.

Orchestrator Protocol

You are the conductor. Agents play the music.

  • Explore finds -> Librarian reads -> Plan designs -> Advisor scans -> Risk-assessor evaluates risk -> Critic reviews -> general-purpose implements -> Validator checks
  • Launch independent agents in parallel (one message, multiple Agent calls)
  • Sequential when dependent: wait for Explore paths before librarian reads them
  • Declare intent before delegating: which agent, what task, expected output
  • Trust but verify: spot-check critical claims from agents
SituationDo This
Find filesAgent(Explore)
Understand codeAgent(librarian)
Git recon (tags, branches, commits)Agent(Explore)
Git analysis (diffs, changelogs)Agent(librarian)
Implement featureAgent(general-purpose) with spec
Verify workAgent(validator)
Gap analysis before planningAgent(advisor)
Risk pass before plan approvalAgent(oh-my-claude:risk-assessor)
Complex taskAgent(Plan) first
Review plan before executionAgent(critic)
Security auditAgent(oh-my-claude:security-auditor)

Ultrawork Mode

Context protection is always on. Ultrawork adds execution intensity.

Triggers

ultrawork or ulw

Behaviors

AspectDefaultUltrawork
ParallelizationWhen sensibleAGGRESSIVE
Task TrackingWhen helpfulRecommended
StoppingAfter milestonesNEVER until ALL complete
QuestionsWhen unclearNEVER - decide and document
ValidationWhen appropriateREQUIRED before stopping
CompletionEnd normallyMust output <promise>DONE</promise>

External Memory

Use Claude Code auto-memory for durable context via /memory.

Protocol:

  • Save key decisions, learnings, and blockers with /memory before context fills up
  • Review relevant memory entries when resuming work or after /prime
  • Include important memory context in agent delegations

Ultra Plan Mode

Auto-activates when entering native plan mode (no keyword needed).

What It Does

PhaseBehavior
ResearchMandatory Explore + librarian before designing
AnalysisMust consider 2+ approaches with tradeoffs
RiskFor non-trivial changes, run risk-assessor before plan approval
ReviewCritic agent MUST approve before ExitPlanMode
HandoffPlan path saved for execution session

Plan→Execution Transition

When you approve a plan (ExitPlanMode):

  1. Claude Code preserves the plan content
  2. "Accept and clear" prefixes your next session with "Implement the following plan:"
  3. ultrawork_detector injects execution context based on this prefix

Agent Teams

Coordinate multiple Claude Code sessions working together.

When to Use Teams vs Subagents

Use Subagents (default)Use Agent Teams
Focused tasks where only results matterTasks needing inter-agent discussion
Sequential workIndependent modules in parallel
Same-file editsResearch/review from multiple angles
Dependency chainsCompeting hypotheses or cross-layer work

Subagents are cheaper and simpler. Use teams only when parallel collaboration adds real value.

How It Works

Create teams with natural language - there is no tool-based API:

  • "Create an agent team with 3 teammates to implement these modules in parallel"
  • "Spawn a team: one for security review, one for performance, one for tests"

Key properties:

  • Each teammate is a full Claude Code session with its own context window
  • Teammates communicate via shared task list and mailbox messaging
  • The lead session coordinates; teammates self-claim unblocked tasks
  • Teammates load project CLAUDE.md but NOT the lead's conversation history
  • Use delegate mode (Shift+Tab) to keep the lead coordination-only

Rules

  • Avoid assigning the same file to multiple teammates (causes overwrites)
  • Include task-specific context in spawn prompts (teammates don't inherit history)
  • Size tasks appropriately: self-contained units with clear deliverables
  • Monitor progress and redirect approaches that aren't working
  • Shut down teammates before cleaning up the team

See official docs for full reference.

Other Keywords

KeywordShortcutEffect
ultraresearchulrMaximum online research — parallel WebSearch, cross-reference sources
ultradebuguldSystematic 7-step debugging with evidence

Commands

CommandPurpose
/primeContext recovery after /clear

Skills

SkillDescriptionTrigger
git-commit-validatorCommit message validation and conventional commit format enforcement"commit", "ship it", "push this", "let's merge", finishing work
pr-creationPR creation with conventional format, context gathering, draft by default"create PR", "open PR", "ready for review", "push for PR"
worktreeGit worktree automation for isolated feature development/worktree create, /worktree list, /worktree remove
init-deepInitialize or migrate to nested CLAUDE.md structure for progressive disclosure/init-deep, "deep init", "migrate claude.md", "nested claude"
ralph-planStructured PRD generation with interview, research, and approval workflow/ralph-plan <topic>, "create prd", "generate prd", "plan this"
ralph-loop-initTransform approved plans into executable ralph loop infrastructure/ralph-loop-init, /ralph-init, "setup ralph loop"
debuggerSystematic debugging methodology for diagnosing failures and root cause analysis2+ failed fix attempts, "ultradebug", "uld", debugging in circles
tddTDD methodology for writing tests first, Red-Green-Refactor cycle"tdd", "test first", "test driven", "red green refactor"
verificationEvidence-based verification before claiming work is complete"verify", "verification", "is it done", "complete", "ready to merge"
receiving-code-reviewHow to handle code review feedback with technical rigor"review feedback", "address review", "fix review comments"
writing-skillsMethodology for creating effective skills using TDD principles"create skill", "write skill", "new skill", "skill authoring"
oh-my-claude-runtimeRuntime workflow guidance for ultrawork modes, orchestration, and plugin configurationoh-my-claude behavior, ultrawork, plan execution

Hooks (Automatic)

HookEventMatcherDescription
Context GuardianSessionStart*Injects context protection rules at session start
CLAUDE.md HealthSessionStart*Checks CLAUDE.md health, warns about size/staleness issues
OpenKanban StatusSessionStart, PreToolUse, PermissionRequest, UserPromptSubmit, Stop*Writes agent status when in OpenKanban terminal (via OPENKANBAN_SESSION)
Ultrawork DetectorUserPromptSubmit*Detects ultrawork/ultradebug/ultraresearch keywords, adjusts intensity
Danger BlockerPreToolUseBashWarns on risky patterns (curl piped to shell); catastrophic blocking moved to Safe Permissions
Commit Quality EnforcerPreToolUseBashEnforces commit message quality and conventional commit format
TDD EnforcerPreToolUseEdit|WriteEnforces TDD by requiring test files before source edits (via OMC_TDD_MODE)
Delegation EnforcerPreToolUseEdit|WriteContext guidance encouraging delegation to specialized agents
Safe PermissionsPermissionRequestBash, Read|Glob|Grep, Write|EditAuto-approves safe commands (tests, linters, readonly git, Claude internal paths), denies catastrophic commands
Plan Execution InjectorPostToolUseExitPlanModeInjects execution context and agent teams guidance after plan approval
Context MonitorPostToolUse*Warns at 70%+ context usage, critical at 85%
Edit Error RecoveryPostToolUse*Detects Edit tool failures, injects recovery guidance
Agent Usage ReminderPostToolUse*Reminds to delegate to agents instead of using search tools directly
Verification ReminderPostToolUse*Reminds to verify agent claims after Task completion
Todo EnforcerStop*Prevents stopping when todos are incomplete
Notification AlertStop, Notification*, permission_prompt|idle_promptDesktop notifications, opt-in via OMC_NOTIFICATIONS=1
PreCompact ContextPreCompact*Preserves session state + semantic patterns before compaction

Configuration

Customize behavior via environment variables in your settings.json:

{
  "env": {
    "OMC_CONTEXT_WARN_PCT": "70"
  }
}
VariableDefaultDescription
OMC_CONTEXT_WARN_PCT70Context % to trigger warning
OMC_CONTEXT_CRITICAL_PCT85Context % for critical warning
OMC_SAFE_PERMISSIONS1Set to 0 to disable auto-approvals
OMC_TDD_MODEoffTDD enforcement: off, guided, enforced
OMC_DANGER_BLOCK1Set to 0 to disable catastrophic command blocking
OMC_NOTIFICATIONS0Set to 1 to enable desktop notifications on Stop
OMC_USE_TASK_SYSTEM1Enable Task system checking for incomplete todos on Stop
OMC_STOP_CHECK_GIT0Set to 1 to check for uncommitted git changes on Stop
OMC_STOP_CHECK_PLANS1Check for incomplete plans on Stop
OPENKANBAN_SESSION(unset)OpenKanban terminal session ID for status integration
HOOK_DEBUG(unset)Set to 1 to enable hook debug logging to stderr

PR Creation

This skill MUST be invoked whenever you are creating a pull request. It handles the complete workflow from context gathering to PR submission with consistent formatting.

When This Skill Activates

Auto-invoke this skill when the user implies a PR should be created:

CategoryTrigger Phrases
Explicit PR"create PR", "open PR", "make PR", "create a pull request"
Review intent"ready for review", "review ready", "send for review"
Push for PR"push for PR", "push and PR", "push and create PR"
Submission"submit for review", "open pull request", "make a pull request"

Key insight: If the user's intent results in gh pr create being run, this skill MUST be used first.

Do NOT run gh pr create without this skill.

Complete PR Creation Workflow

Step 1: Gather Context

git status                              # Check working tree state
git diff HEAD                           # See uncommitted changes (if any)
git log main..HEAD --oneline            # Commits to be included in PR
git diff main...HEAD                    # Full diff against base branch
git branch --show-current               # Current branch name

Important: Ensure all changes are committed before creating PR. If uncommitted changes exist, use the git-commit-validator skill first.

Step 2: Determine Base Branch

Check for common base branch names:

git rev-parse --verify main 2>/dev/null && echo "main" || git rev-parse --verify master 2>/dev/null && echo "master"

Or check remote default:

gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'

Step 3: Generate PR Title

Format: type(scope): description (conventional commits)

Rules:

  • Max 50 characters
  • Lowercase type from: feat, fix, docs, refactor, test, chore, perf, ci, build, style, revert
  • Optional scope in parentheses
  • Imperative mood ("add" not "added")
  • No period at end

Title should summarize the entire PR, not just the last commit.

Analyze all commits in the PR:

git log main..HEAD --oneline

Synthesize into a single title that captures the overall change.

Step 4: Generate PR Body

Use this exact format:

## Summary
[1-3 sentences explaining what this PR does and why]

## Changes
- [Bullet list of key changes]
- [Focus on what matters, not every file touched]

## Test Plan
[How changes were validated - tests run, manual verification, etc.]

Closes #123

Body Guidelines:

  • Summary: Brief context for reviewers, focus on WHY
  • Changes: Key modifications, not exhaustive file list
  • Test Plan: How you verified the changes work
  • Issue reference: Include if applicable (Closes, Fixes, Resolves)

Step 5: Create PR

Default: Create as draft (per project standards)

Use HEREDOC for proper body formatting:

gh pr create --draft --title "type(scope): description" --body "$(cat <<'EOF'
## Summary
Brief explanation of what and why.

## Changes
- Key change 1
- Key change 2

## Test Plan
How this was tested.

Closes #123
EOF
)"

For ready-for-review PRs (when user explicitly requests):

gh pr create --title "..." --body "..."

Validation Rules

Title Validation

  1. Max 50 characters - Truncate or rephrase if over
  2. Format check - Must match: ^[a-z]+(\([a-z0-9\-]+\))?!?: .+$
  3. Valid type - One of: feat, fix, docs, refactor, test, chore, perf, ci, build, style, revert
  4. Imperative mood - "add feature" not "added feature"
  5. No period at end

Body Validation

  1. Has Summary section - Required
  2. Has Changes section - Required (at least one bullet)
  3. Has Test Plan section - Required
  4. Concise - 2-3 paragraphs max in summary
  5. No AI attribution - No "Generated by", "Created with AI", etc.

Pre-flight Checks

Before creating PR:

  1. Branch has commits ahead of base
  2. No uncommitted changes (or commit them first)
  3. Branch is pushed to remote
  4. No existing PR for this branch (unless intentional)
# Check if PR already exists
gh pr list --head "$(git branch --show-current)" --state open

Type Reference

TypeUse For
featNew feature or capability
fixBug fix
docsDocumentation only
refactorCode restructuring (no behavior change)
perfPerformance improvement
testTest additions/fixes
choreMaintenance, deps, config
ciCI/CD changes
buildBuild system changes
styleFormatting (no logic change)
revertReverting previous changes

Examples

Simple Feature PR

Title:

feat(auth): add OAuth2 login support

Body:

## Summary
Adds Google OAuth2 as an authentication option alongside existing email/password login.

## Changes
- Add OAuth2 provider configuration
- Create OAuth callback handler
- Add "Login with Google" button to login page

## Test Plan
- Tested OAuth flow locally with test credentials
- Verified token refresh works correctly
- Existing email login still works

Closes #45

Bug Fix PR

Title:

fix(api): resolve timeout on large file uploads

Body:

## Summary
Large file uploads were timing out due to default 30s limit. Increased timeout and added progress tracking.

## Changes
- Increase upload timeout to 5 minutes
- Add upload progress callback
- Better error messages for timeout scenarios

## Test Plan
- Uploaded 500MB file successfully
- Verified timeout error message when server unreachable

Fixes #128

Refactoring PR

Title:

refactor: consolidate auth middleware

Body:

## Summary
Auth checks were scattered across three middleware files. Consolidated into single auth module for consistency.

## Changes
- Merge auth middleware into single module
- Update route imports
- Remove deprecated auth helpers

## Test Plan
- All existing auth tests pass
- Manual verification of protected routes

Why Draft by Default?

Draft PRs signal the work is ready for early feedback but may not be complete. Benefits:

  • Allows CI to run before requesting reviews
  • Enables async collaboration on in-progress work
  • Prevents accidental merges of incomplete work
  • Clear signal when ready: mark ready for review

To create a non-draft PR, user must explicitly request it.

Error Handling

ErrorResolution
No commits ahead of baseEnsure work is committed
Branch not pushedPush with git push -u origin HEAD
PR already existsShow existing PR URL, ask if update intended
Auth failureRun gh auth login
Title too longShorten or rephrase

Ralph Loop Init Skill

Transform approved plans into executable ralph loop infrastructure.

What is Ralph Loop?

Ralph Loop is an autonomous execution system that runs Claude (or compatible tools) in a loop to complete multi-step implementation work. It transforms a PRD into:

  1. prd.json - Machine-readable stories with progress tracking
  2. loop.py - Python UV script that orchestrates iterations with rich output
  3. CLAUDE.md - Per-iteration instructions for the AI
  4. progress.txt - Human-readable execution log
  5. guardrails.md - Quality gates and constraints

Each iteration: read one story, implement it, run quality gates, commit, update progress, exit. The loop script handles the next iteration.

When This Skill Activates

CategoryTrigger Phrases
Initialize/ralph-loop-init <plan-path>, /ralph-init <plan-path>
Setupsetup ralph loop, generate ralph loop
From plancreate ralph loop from .claude/plans/...

Workflow

Phase 1: Plan Selection

Identify the approved plan to transform.

If path provided:

/ralph-loop-init .claude/plans/user-authentication.md

Read the plan at the specified path.

If no path provided:

/ralph-loop-init

List available plans in .claude/plans/ (excluding drafts/) and ask user to select one.

Validation:

  • Plan file must exist
  • Plan must have "## Implementation Steps" section
  • Plan should be in .claude/plans/ (not drafts/)

Phase 2: Pre-flight Check

Before generating files, check for existing ralph loop infrastructure.

if [ -d ".ralph" ]; then
    # Existing ralph loop detected
fi

If .ralph/ exists:

Present options to user:

Existing ralph loop detected at .ralph/

Options:
1. "overwrite" - Delete existing .ralph/ and create fresh
2. "resume" - Keep existing, show current progress
3. "cancel" - Abort initialization

Which would you like?

Handle response:

User SaysAction
"overwrite", "fresh", "start over"Delete .ralph/, proceed with generation
"resume", "continue", "keep"Show progress from existing prd.json, do not regenerate
"cancel", "abort", "stop"Exit skill

Phase 3: Story Extraction

Parse the plan's "## Implementation Steps" section into structured stories.

Input format (from plan):

## Implementation Steps

1. Create the auth middleware in src/middleware/auth.ts with JWT validation logic
2. Add login endpoint to src/routes/auth.ts that validates credentials and returns tokens
3. Add logout endpoint that invalidates the current token
4. Create token refresh endpoint for extending sessions
5. Update User model with password hashing using bcrypt

Extraction rules:

  1. Find the "## Implementation Steps" section
  2. Parse numbered list items (1., 2., 3., etc.)
  3. For each item:
    • id: story-{N} where N is the step number
    • title: First sentence or line of the step (truncated at 80 chars if needed)
    • description: Full step text
    • priority: Sequential (1, 2, 3...) based on order
    • passes: false (all stories start incomplete)

Output structure:

{
  "stories": [
    {
      "id": "story-1",
      "title": "Create auth middleware with JWT validation",
      "description": "Create the auth middleware in src/middleware/auth.ts with JWT validation logic",
      "priority": 1,
      "passes": false
    }
  ]
}

Phase 4: Quality Detection

Detect project quality gates by scanning for common configuration files.

Detection Logic:

File/PatternQuality Gate Command
package.json with scripts.testnpm test
package.json with scripts.lintnpm run lint
tsconfig.jsonnpx tsc --noEmit
.eslintrc* or eslint.config.*npx eslint .
pytest.ini or pyproject.toml with pytestpytest
Makefile with test targetmake test
Makefile with lint targetmake lint
.github/workflows/*.ymlNote: "CI will run on push"

Detection process:

  1. Check for package.json:

    if [ -f "package.json" ]; then
        # Check for test/lint scripts
    fi
    
  2. Check for TypeScript:

    if [ -f "tsconfig.json" ]; then
        # Add tsc --noEmit
    fi
    
  3. Check for ESLint:

    if ls .eslintrc* eslint.config.* 2>/dev/null; then
        # Add eslint
    fi
    
  4. Check for Python testing:

    if [ -f "pytest.ini" ] || grep -q "pytest" pyproject.toml 2>/dev/null; then
        # Add pytest
    fi
    
  5. Check for Makefile targets:

    if [ -f "Makefile" ]; then
        grep -q "^test:" Makefile && # Add make test
        grep -q "^lint:" Makefile && # Add make lint
    fi
    

Output: List of quality gate commands for CLAUDE.md template.


Phase 5: File Generation

Generate all ralph loop files in .ralph/ directory.

Create Directory Structure
mkdir -p .ralph
File 1: prd.json
{
  "plan_source": ".claude/plans/{topic-slug}.md",
  "created_at": "{ISO-8601-timestamp}",
  "stories": [
    {
      "id": "story-1",
      "title": "{extracted title}",
      "description": "{full step description}",
      "priority": 1,
      "passes": false
    },
    {
      "id": "story-2",
      "title": "{extracted title}",
      "description": "{full step description}",
      "priority": 2,
      "passes": false
    }
  ]
}
File 2: progress.txt
Ralph Loop Progress
===================
Plan: {plan title}
Source: {plan path}
Started: {timestamp}

Stories: 0/{total} complete

---

[Execution log will appear below]
File 3: CLAUDE.md
# Ralph Loop Task

You are executing ONE iteration of a ralph loop. Complete ONE story, then exit.

## Your Task

1. Read `.ralph/prd.json` to find the next incomplete story (passes: false, lowest priority)
2. Implement ONLY that story
3. Run quality gates
4. Commit your changes
5. Update progress
6. Exit

## Quality Gates

Run these commands before committing. ALL must pass:

{detected quality gate commands, one per line with backticks}

If any gate fails, fix the issue before committing.

## Story Completion Protocol

When you complete a story:

1. **Check for changes and commit if needed:**
   ```bash
   git status --porcelain

If there ARE changes:

  • Stage changes: git add -A
  • Commit with a conventional commit message describing your implementation
  • The commit_quality_enforcer hook validates format automatically
  • If commit is rejected, read the error, fix the message, retry (max 3 attempts)
  • After 3 failures, log the error to progress.txt and exit

If there are NO changes, proceed directly to step 2.

  1. Update prd.json:

    • Set passes: true for the completed story
  2. Append to progress.txt:

    [{timestamp}] Completed: {story-id} - {story-title}
    
  3. Exit immediately - Do not start another story

Guardrails

See .ralph/guardrails.md for constraints and boundaries.

Important

  • Complete exactly ONE story per iteration
  • Do not skip quality gates
  • Do not modify stories you are not implementing
  • If blocked, document in progress.txt and exit
  • Trust the loop script to handle the next iteration

#### File 4: loop.py

```python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["rich"]
# ///
"""
Ralph Loop Runner

Executes AI iterations until all stories complete.
Uses rich for beautiful terminal output with progress tracking.
"""

import json
import os
import subprocess
import sys
from pathlib import Path

from rich.console import Console
from rich.panel import Panel

console = Console()

RALPH_DIR = Path(".ralph")
PRD_FILE = RALPH_DIR / "prd.json"
PROGRESS_FILE = RALPH_DIR / "progress.txt"


def load_prd() -> dict:
    """Load and return the PRD JSON."""
    with open(PRD_FILE) as f:
        return json.load(f)


def count_stories(prd: dict) -> tuple[int, int]:
    """Return (complete, total) story counts."""
    stories = prd["stories"]
    complete = sum(1 for s in stories if s["passes"])
    return complete, len(stories)


def get_next_story(prd: dict) -> dict | None:
    """Get the next incomplete story by priority."""
    incomplete = [s for s in prd["stories"] if not s["passes"]]
    return min(incomplete, key=lambda s: s["priority"]) if incomplete else None


def run_claude() -> int:
    """Run claude and return exit code."""
    result = subprocess.run([
        "claude",
        "--dangerously-skip-permissions",
        "--print",
        "Execute ralph loop iteration per .ralph/CLAUDE.md"
    ])
    return result.returncode


def show_header(max_iterations: int, complete: int, total: int):
    """Display the header panel with autonomous mode warning."""
    console.print(Panel.fit(
        f"[bold cyan]Ralph Loop Runner[/]\n\n"
        f"[bold yellow]⚠️  AUTONOMOUS MODE ENABLED[/]\n"
        f"[dim]Commands execute without approval[/]\n\n"
        f"[dim]Max:[/] [yellow]{max_iterations}[/]  "
        f"[dim]Progress:[/] [green]{complete}[/]/[cyan]{total}[/]",
        border_style="blue",
        title="🔄 ralph",
        title_align="left"
    ))


def show_iteration(iteration: int, max_iterations: int, story: dict, remaining: int):
    """Display iteration info."""
    console.print()
    console.rule(f"[bold]Iteration {iteration}/{max_iterations}[/]", style="dim")
    console.print(f"[cyan]Next:[/] {story['id']} - {story['title']}")
    console.print(f"[dim]Remaining:[/] {remaining} stories")
    console.print()


def show_progress_bar(complete: int, total: int):
    """Display a simple progress indicator."""
    pct = (complete / total * 100) if total > 0 else 0
    filled = int(pct / 5)
    bar = "█" * filled + "░" * (20 - filled)
    console.print(f"[cyan]Progress:[/] [{bar}] {complete}/{total} ({pct:.0f}%)")


def show_completion():
    """Display completion panel."""
    console.print()
    console.print(Panel.fit(
        "[bold green]✓ All stories complete![/]",
        border_style="green"
    ))


def show_max_reached(max_iterations: int, incomplete: int):
    """Display max iterations panel."""
    console.print()
    console.print(Panel.fit(
        f"[bold yellow]Max iterations reached ({max_iterations})[/]\n"
        f"[red]{incomplete} stories still incomplete[/]",
        border_style="yellow"
    ))


def main():
    max_iterations = int(os.environ.get("MAX_ITERATIONS", "10"))

    # Verify ralph directory
    if not RALPH_DIR.exists():
        console.print("[red]Error:[/] .ralph directory not found")
        console.print("[dim]Run /ralph-loop-init first[/]")
        sys.exit(1)

    if not PRD_FILE.exists():
        console.print(f"[red]Error:[/] {PRD_FILE} not found")
        sys.exit(1)

    # Load PRD and show header
    prd = load_prd()
    complete, total = count_stories(prd)
    show_header(max_iterations, complete, total)

    # Main loop
    for iteration in range(1, max_iterations + 1):
        prd = load_prd()  # Reload each iteration
        complete, total = count_stories(prd)
        incomplete = total - complete

        if incomplete == 0:
            show_completion()
            sys.exit(0)

        next_story = get_next_story(prd)
        show_iteration(iteration, max_iterations, next_story, incomplete)

        # Run claude with visible output
        with console.status("[bold green]Starting claude...[/]", spinner="dots"):
            pass  # Brief status then let subprocess take over

        exit_code = run_claude()

        if exit_code != 0:
            console.print(f"[yellow]Warning:[/] claude exited with code {exit_code}")

        # Show updated progress
        prd = load_prd()
        complete, total = count_stories(prd)
        show_progress_bar(complete, total)

    # Max iterations reached
    prd = load_prd()
    complete, total = count_stories(prd)
    incomplete = total - complete
    show_max_reached(max_iterations, incomplete)
    sys.exit(1 if incomplete > 0 else 0)


if __name__ == "__main__":
    main()
File 5: guardrails.md
# Ralph Loop Guardrails

Constraints and boundaries for this ralph loop execution.

## Scope Boundaries

This loop implements the plan at: `{plan_source}`

### In Scope
- Stories defined in prd.json
- Files mentioned in the original plan
- Quality gates listed in CLAUDE.md

### Out of Scope
- Features not in the plan
- Refactoring unrelated code
- Dependency upgrades (unless specified)
- Documentation beyond code comments

## Quality Requirements

All changes must:
1. Pass defined quality gates
2. Include appropriate tests (if test infrastructure exists)
3. Follow existing code patterns
4. Not break existing functionality

## Commit Standards

- One commit per story
- Conventional commit format: `feat(ralph): {description}`
- Include `Story-Id: {story-id}` in commit body
- No unrelated changes in commits

## Blocking Conditions

Stop and document in progress.txt if:
- Quality gates fail after 3 attempts
- Story requires clarification not in plan
- External dependency is unavailable
- Circular dependency detected

## Recovery

If the loop fails:
1. Check progress.txt for last successful story
2. Check git log for committed work
3. Review prd.json for story states
4. Resume with: `uv run .ralph/loop.py`

## Manual Override

To skip a problematic story:
```bash
# Edit prd.json, set passes: true for the story
# Add note to progress.txt explaining skip
# Run: uv run .ralph/loop.py

---

### Phase 6: Completion Report

After generating all files, report to user:

Ralph Loop Initialized

Directory: .ralph/

Files created:

  • prd.json ({N} stories extracted)
  • progress.txt (execution log)
  • CLAUDE.md (per-iteration instructions)
  • loop.py (Python UV script with rich output)
  • guardrails.md (constraints)

Quality gates detected:

  • {list of detected gates}

⚠️ AUTONOMOUS MODE This loop runs with --dangerously-skip-permissions Claude will execute commands without prompting for approval Review .ralph/guardrails.md before starting

To start the loop: uv run .ralph/loop.py

Plan source: {plan_path}


---

## Examples

### Example 1: Initialize with Plan Path

/ralph-loop-init .claude/plans/user-authentication.md


**Output:**

Ralph Loop Initialized

Directory: .ralph/

Files created:

  • prd.json (6 stories extracted)
  • progress.txt (execution log)
  • CLAUDE.md (per-iteration instructions)
  • loop.py (Python UV script with rich output)
  • guardrails.md (constraints)

Quality gates detected:

  • npm test
  • npm run lint
  • npx tsc --noEmit

⚠️ AUTONOMOUS MODE This loop runs with --dangerously-skip-permissions Claude will execute commands without prompting for approval Review .ralph/guardrails.md before starting

To start the loop: uv run .ralph/loop.py

Plan source: .claude/plans/user-authentication.md


### Example 2: Initialize Without Path

/ralph-init


**Output:**

Available plans:

  1. .claude/plans/user-authentication.md
  2. .claude/plans/api-refactor.md
  3. .claude/plans/test-coverage.md

Which plan should I use for the ralph loop?


User: "2"

**Proceeds with:** `.claude/plans/api-refactor.md`

### Example 3: Existing .ralph/ Directory

setup ralph loop


**Output:**

Existing ralph loop detected at .ralph/

Current progress: 3/8 stories complete Last activity: 2024-01-15 14:30

Options:

  1. "overwrite" - Delete existing .ralph/ and create fresh
  2. "resume" - Keep existing, show current progress
  3. "cancel" - Abort initialization

Which would you like?


User: "overwrite"

**Proceeds with:** Fresh initialization, deleting old .ralph/

---

## Error Handling

### Plan Not Found

Error: Plan not found at {path}

Check that:

  1. The file path is correct
  2. The plan has been approved (not in drafts/)
  3. The file has .md extension

Available plans: {list .claude/plans/*.md}


### No Implementation Steps

Error: No implementation steps found in plan

The plan must have a "## Implementation Steps" section with numbered items:

Implementation Steps

  1. First step description
  2. Second step description ...

Please update the plan and try again.


### Existing .ralph/ with Active Work

Warning: Existing ralph loop has uncommitted progress

Last completed: story-3 (2024-01-15 14:30) Uncommitted changes detected in working directory

Options:

  1. "commit-and-overwrite" - Commit current work, then reinitialize
  2. "discard-and-overwrite" - Discard changes, reinitialize
  3. "resume" - Continue existing loop
  4. "cancel" - Abort

Which would you like?


### Quality Gate Detection Failed

Note: No quality gates detected

The loop will run without automated checks. Consider adding:

  • package.json with test/lint scripts
  • Makefile with test/lint targets
  • pytest configuration

Proceeding with generation...


---

## Behavior Rules

### MUST DO

- Read and validate the plan before generating files
- Extract ALL implementation steps as stories
- Detect quality gates from project configuration
- Generate ALL 5 files (prd.json, progress.txt, CLAUDE.md, loop.py, guardrails.md)
- Report completion with next steps
- Handle existing .ralph/ gracefully

### MUST NOT

- Generate partial file sets
- Skip story extraction validation
- Overwrite .ralph/ without user confirmation
- Modify the source plan file
- Start executing the loop (only initialize)
- Hardcode quality gates without detection
- Create .ralph/ outside project root

### SHOULD DO

- Preserve original plan reference in prd.json
- Include timestamps in generated files
- Provide clear error messages with recovery steps
- Detect as many quality gates as possible
- Format generated files for readability
- Include docstrings in loop.py for clarity

Ralph Plan Skill

Structured PRD generation. Interview, research, plan, approve.

What is Ralph Plan?

Ralph Plan creates comprehensive Product Requirements Documents through a deliberate process:

  1. Interview Phase - Understand requirements through focused questions
  2. Research Phase - Analyze codebase via Explore/librarian
  3. Planning Phase - Generate structured plan with clear steps
  4. Approval Gate - User reviews, modifies, and approves the final PRD

The result is a battle-tested plan ready for implementation by any method the user chooses.

When This Skill Activates

CategoryTrigger Phrases
Start planning/ralph-plan <topic>, create prd, generate prd, plan this
Check statusralph-plan status
Resumeresume ralph-plan

Workflow

Phase 1: Planning

Create a structured plan through interview and research.

Step 1: Initialize Draft

Create draft at .claude/plans/drafts/{topic-slug}.md with template:

# Planning Draft: {topic}

## Status
Phase: Interview
Started: {timestamp}

## Requirements
- [to be captured from interview]

## Decisions
- [choices made during interview]

## Research Findings
- [results from Explore/librarian]

## Open Questions
- [unanswered items]
Step 2: Interview

Conduct focused interview (3-5 questions based on complexity):

Core Questions:

  1. "What problem does this solve?" (understand context)
  2. "What's the scope - minimal viable vs complete?" (set boundaries)
  3. "Any constraints, non-goals, or things to avoid?" (define exclusions)

Follow-up Questions (as needed):

  • Technical approach preferences
  • Dependencies on other work
  • Success criteria

Update draft after each answer.

Step 3: Research

Research the codebase before finalizing:

Agent: Explore
Task: Find relevant files for {topic}
Expected: List of files that will be affected
Agent: oh-my-claude:librarian
Task: Read and summarize key files
Expected: Summary of current implementation patterns

Add findings to draft under "## Research Findings".

Step 4: Generate Plan

Transform draft into structured plan with these sections:

# Plan: {topic}

## Context
[Why this plan exists, what problem it solves]

## Objectives

### Must Have
- [required outcomes]

### Must NOT
- [explicit exclusions and constraints]

## Implementation Steps
1. [Step with specific file references]
2. [Step with specific file references]
3. ...

## Files to Modify
| File | Changes |
|------|---------|
| `path/to/file.ts` | [what changes] |

## Acceptance Criteria
- [ ] [Testable criterion]
- [ ] [Testable criterion]
- [ ] [Testable criterion]

Phase 2: Approval Gate

User must review and approve the plan before finalization.

Present the Plan
  1. Display the complete plan summary to the user
  2. Use AskUserQuestion tool for approval:
{
  "questions": [{
    "question": "How would you like to proceed with this PRD?",
    "header": "PRD Status",
    "options": [
      {"label": "Approve", "description": "Finalize and save the PRD"},
      {"label": "Request Changes", "description": "Modify specific sections"},
      {"label": "Cancel", "description": "Abort and keep draft"}
    ],
    "multiSelect": false
  }]
}

CRITICAL: You MUST use the AskUserQuestion tool for approval. Do NOT output text prompts asking the user to "reply with" something.

Handle User Response
User ResponseAction
"Approve"Finalize PRD (move to final location)
"Request Changes"Ask what to change, update plan, re-present with AskUserQuestion
"Cancel"Keep draft, do not finalize
"Other" (custom text)Interpret and act accordingly, then re-prompt if needed

Do NOT interpret ambiguous responses as approval. If unclear, re-prompt with AskUserQuestion.

On Approval
  1. Move plan from draft to final location:

    .claude/plans/drafts/{topic-slug}.md  -->  .claude/plans/{topic-slug}.md
    
  2. Delete the draft file

  3. Report completion:

    PRD finalized at .claude/plans/{topic-slug}.md
    
    Next steps:
    - Review the plan at your convenience
    - Implement manually, or use your preferred automation
    - Reference the acceptance criteria to track progress
    

Status Checking

When user says ralph-plan status:

Ralph Plan Status
=================

**Plan:** {topic}
**Phase:** Interview | Research | Draft Complete | Awaiting Approval | Finalized

--- Plan Location ---
Draft: .claude/plans/drafts/{topic-slug}.md
Final: .claude/plans/{topic-slug}.md (if finalized)

--- Plan Contents ---
Steps: {total}
Acceptance Criteria: {total}
Files Affected: {count}

Examples

Example 1: Feature Implementation PRD

/ralph-plan implement user authentication with JWT

Interview Phase:

  • Q: "What problem does this solve?"
  • A: "Users need to log in securely"
  • Q: "What's the scope?"
  • A: "Basic login/logout with token refresh"
  • Q: "Any constraints?"
  • A: "Must use existing user model, no OAuth"

Research Phase:

  • Explore finds: src/models/User.ts, src/routes/index.ts
  • Librarian summarizes: Uses Express, no existing auth middleware

Plan Generated:

  • 6 implementation steps
  • 4 files to modify
  • 4 acceptance criteria

Approval:

Plan presented to user with AskUserQuestion tool. User selects: "Approve"

Output:

PRD finalized at .claude/plans/user-authentication-jwt.md

Example 2: Refactoring PRD with Modifications

/ralph-plan refactor the API to use dependency injection

Interview Phase:

  • Q: "Which services should use DI?"
  • A: "All services in src/services/"
  • Q: "Testing implications?"
  • A: "Should make mocking easier"

Research Phase:

  • Explore finds: 8 service files, current instantiation patterns
  • Librarian summarizes: Direct instantiation, no DI container

Plan Generated:

  • 12 implementation steps
  • Container setup, service refactoring

Approval: User selects "Request Changes" via AskUserQuestion, specifies "change step 5 to use factory pattern"

Updated Plan: Step 5 modified, re-presented with AskUserQuestion

Second Approval: User selects "Approve"

Output:

PRD finalized at .claude/plans/api-dependency-injection.md

Example 3: Test Coverage PRD

create prd for adding test coverage to src/services/

Interview Phase:

  • Q: "Unit tests only, or integration too?"
  • A: "Both"
  • Q: "Coverage target?"
  • A: "80% minimum"

Research Phase:

  • Explore finds: 6 service files, existing test patterns
  • Librarian summarizes: Jest setup exists, 2 services have tests

Plan Generated:

  • Test file for each untested service
  • Integration test suite
  • Coverage configuration

Approval: User approves

Output:

PRD finalized at .claude/plans/service-test-coverage.md

Decision Matrices

Complexity Detection

SignalComplexityInterview Depth
"just", "simple", "quick"Simple2-3 questions
Specific file mentionedStandard3-4 questions
"redesign", "overhaul"Complex5-6 questions
Multiple systems involvedComplex6+ questions

When to Skip Research

ScenarioSkip?
User provides full context and file pathsYes
Simple config changeYes
New feature in unfamiliar areaNo
Refactoring existing codeNo

Error Handling

User Cancels During Planning

  1. Confirm: "Cancel planning for '{topic}'?"
  2. If confirmed: Keep draft at .claude/plans/drafts/{topic-slug}.md
  3. Report: "Planning cancelled. Draft saved for later."

User Cancels at Approval Gate

  1. Keep plan at draft location
  2. Report: "PRD not finalized. Draft preserved at .claude/plans/drafts/{topic-slug}.md"

Behavior Rules

MUST DO

  • Complete full planning phase before approval gate
  • Display complete plan to user before finalization
  • Use AskUserQuestion tool for approval (NEVER use text prompts)
  • Wait for explicit approval via tool response
  • Move plan from drafts/ to final location on approval
  • Delete draft after successful finalization

MUST NOT

  • Finalize PRD without explicit user approval
  • Use text prompts for approval (ALWAYS use AskUserQuestion tool)
  • Interpret silence or ambiguous responses as approval
  • Skip the interview or research phases
  • Finalize with incomplete or vague plans
  • Delete draft files without confirmation
  • Proceed to any implementation/execution

SHOULD DO

  • Keep interview concise (3-5 questions)
  • Research codebase before finalizing plan
  • Break complex plans into clear steps
  • Include testable acceptance criteria
  • Preserve drafts for resumability

Integration Notes

Relationship to /plan

Ralph Plan uses an enhanced version of the /plan methodology:

  • Same draft structure
  • Same interview approach
  • Same research phase
  • Same final plan format

The difference: Ralph Plan has a formal approval gate and structured workflow.

State Files Location

.claude/
  plans/
    drafts/
      {topic-slug}.md      # During planning (before approval)
    {topic-slug}.md        # After approval (final PRD)

Receiving Code Review Skill

How to handle review feedback with technical rigor, not performative agreement.

When to Apply

  • After receiving code-reviewer agent output
  • PR review comments from teammates or external reviewers
  • External feedback on implementation decisions
  • When told to "address review comments" or "fix review feedback"

Response Pattern

READ -> UNDERSTAND -> VERIFY -> EVALUATE -> RESPOND -> IMPLEMENT

READ

Read the full review. Don't skim, don't react immediately. Take in every comment before acting on any of them. Later comments may contradict or contextualize earlier ones.

UNDERSTAND

For each issue, understand what's actually being flagged. Restate in your own words: "This comment is about X because Y." If you can't restate it, you don't understand it yet.

VERIFY

Check if the reviewer's claim is factually correct. Read the code they reference. Don't assume they're right or wrong -- look at the actual code at {file}:{line}.

EVALUATE

Is this a real issue? Does the suggested fix actually improve things? Is the effort justified given the impact? Not all feedback requires action.

RESPOND

Technical response only:

  • Agree with reasoning: "Correct. The null check is missing at line X. Fixing."
  • Disagree with evidence: "The review flags X, but {file}:{line} shows Y handles this case."
  • Ask for clarification: "The comment suggests X. Is the concern about safety or performance?"

IMPLEMENT

Fix in order: clarify unclear items -> blocking issues -> simple fixes -> complex fixes. Test each fix independently before moving to the next.

Forbidden Responses

These responses indicate you're people-pleasing, not engineering:

  • "You're absolutely right!" -- Performative agreement without understanding
  • "Great point!" -- Flattery is not technical discourse
  • "I'll fix that right away!" -- Understand before acting
  • "Of course, makes total sense!" -- Does it? Or are you people-pleasing?

Instead: "The review identifies X. Checking... [evidence]. This is correct because [reason]. Fixing."

Or: "The review suggests X, but [counter-evidence]. Keeping current approach because [reason]."

Source-Specific Handling

SourceTrust LevelResponse Style
Human partnerHigh contextClarify intent, implement thoughtfully
External reviewerMedium contextVerify claims against code, ask about unknowns
code-reviewer agentSystematic but no contextCross-reference with requirements, verify specifics

When to Push Back

  • Technically incorrect -- "The review suggests X, but the code at {file}:{line} shows Y"
  • YAGNI -- "This adds complexity for a hypothetical scenario. Current implementation handles all existing cases"
  • Breaks existing functionality -- "This change would break {specific behavior} because {evidence}"
  • Missing context -- "The review assumes X, but the requirement specifies Y (see {reference})"

Pushing back is not adversarial. It's quality control. Reviewers benefit from knowing when their feedback misses context.

Implementation Order

  1. Clarify unclear items first (don't build on misunderstanding)
  2. Blocking/critical issues (things that prevent the code from working)
  3. Simple fixes (typos, naming, formatting)
  4. Complex fixes (refactors, architectural changes)
  5. Test each fix independently

Common Mistakes

MistakeWhy It's WrongDo This Instead
Fix everything without reading all commentsLater comments may contradict earlier onesRead ALL comments first
Performative agreementHides misunderstandingRespond with technical reasoning
Batch all fixes in one commitCan't isolate if something breaksOne logical change per commit
Skip re-testing after fixesFixes introduce new bugsTest after every change
Ignore minor issuesThey accumulateFix or explicitly defer with reason

The Bottom Line

Review feedback is data, not judgment. Evaluate it technically, respond with evidence, implement with discipline.

TDD Skill

Write the test. Watch it fail. Make it pass. Clean up. Repeat.

The Iron Law

NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST

If you're writing production code and no test just failed, you're doing it wrong.

When to Apply

  • OMC_TDD_MODE is enabled (guided or enforced)
  • Implementing a new feature or behavior
  • Fixing a bug (write the test that reproduces it first)
  • Unsure how to structure tests for a piece of logic
  • When the tdd_enforcer hook blocks an edit

Red-Green-Refactor Cycle

RED: Write a Failing Test

  1. Write ONE test that describes the desired behavior
  2. Run the test suite
  3. Verify it fails for the RIGHT reason (not a syntax error, not a missing import)
  4. If it passes, your test is wrong or the feature already exists

Verification gate: Test output shows a meaningful failure related to the behavior you're implementing.

GREEN: Make It Pass

  1. Write the MINIMUM code to make the test pass
  2. No extra methods. No abstractions. No "while I'm here" additions
  3. Run the test suite
  4. ALL tests pass (not just the new one)

Verification gate: Full test suite green. Zero failures.

REFACTOR: Clean Up

  1. Remove duplication introduced in the GREEN step
  2. Improve naming, extract methods if warranted
  3. Run the test suite after EVERY change
  4. No new behavior during refactor - tests stay green throughout

Verification gate: Tests still green. Code is cleaner. No new functionality added.

Anti-Rationalization Table

ExcuseCounter
"I'll write tests after"Tests written after prove nothing - they pass immediately
"Too simple to test"Simple code breaks. Test takes 30 seconds
"I know this works"Confidence is not evidence. The test IS the evidence
"Tests will slow me down"Debugging without tests slows you down more
"Just a refactor"Refactors without tests are rewrites without safety nets
"The types guarantee correctness"Types check structure, not behavior. Test the behavior
"It's just a config change"Config changes cause production outages. Test them
"I'll TDD the next one"You said that last time. Start now

Red Flags

Thoughts that signal you're about to violate TDD:

  • "Let me just quickly implement this first..."
  • "This is too obvious to need a test"
  • "I'll come back and add tests"
  • "The test would just be testing the framework"
  • "It's only a one-line change"
  • "I need to see the implementation to know what to test"

If you catch yourself thinking any of these: STOP. Write the test first.

Hook Integration

The tdd_enforcer hook gates file edits when OMC_TDD_MODE is enabled. This skill guides the methodology. The hook fires, you see the gate, invoke this skill for how to proceed.

Flow: Hook blocks edit -> Read the message -> Write/update a test -> Run tests (see RED) -> Now implement (GREEN) -> Clean up (REFACTOR).

When Stuck

ProblemSolution
Can't figure out what to testTest the simplest case first. What's the most basic input/output?
Test is too complexBreak the behavior into smaller units. Test each one
Don't know the test frameworkCheck existing tests in the project. Copy the pattern
Test requires too much setupThat's a design smell. Simplify the interface under test
Multiple things need testingOne test at a time. Pick the smallest behavior first
Existing code has no testsStart with the change you're making. Test the new behavior
Test passes immediatelyYour test isn't testing what you think. Check assertions
Can't make the test failYou might be testing something already implemented. Test the GAP

The Bottom Line

A test that exists before the code proves the code works. A test written after proves nothing but that you can reverse-engineer assertions.

Verification Skill

No evidence, no completion claim. Period.

The Iron Law

NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE

"I think it works" is not evidence. "Tests passed 5 minutes ago" is not fresh. Run the checks NOW, read the output NOW, then claim completion.

When to Apply

  • About to say "done", "complete", or "ready"
  • Before committing or creating a PR
  • After agent teammates claim work is finished
  • When the verification_reminder hook fires
  • Before any handoff to another person or system

Gate Function

IDENTIFY

What needs verification? List every claim you're about to make.

  • Tests pass? Which test suite?
  • Build succeeds? Which build command?
  • Feature works? What specific behavior?
  • No regressions? What could have broken?

RUN

Execute the actual checks. Not "I think they pass" - run them NOW.

  • Run the test suite. Capture output.
  • Run the build. Capture output.
  • Run linters if applicable. Capture output.

READ

Read the output. Actually read it. Don't assume.

  • Check exit codes (0 = success, anything else = failure)
  • Look for warnings that might indicate issues
  • Count passing vs failing tests
  • Verify the output matches expectations

VERIFY

Does the output confirm success? Cross-reference against requirements.

  • Every requirement has corresponding evidence
  • No skipped tests that cover changed behavior
  • No warnings that indicate degraded functionality

CLAIM

Only now can you claim completion. Include the evidence.

Common Failures

ClaimRequiresNot Sufficient
"Tests pass"Fresh test run output"They passed before"
"Build succeeds"Actual build output"It should build"
"Feature works"Demonstrated behavior"I implemented it correctly"
"No regressions"Full test suite run"I only changed one file"
"PR is ready"All checks green"I think it's good"
"Bug is fixed"Reproduction test passes"I addressed the cause"

Anti-Rationalization Table

ExcuseCounter
"The agent said it works"Agents hallucinate. Read the actual output
"I'm confident it works"Confidence is not evidence. Run the check
"I just ran tests a minute ago"You changed code since then. Run again
"It's a trivial change"Trivial changes cause production incidents. Verify
"Tests take too long"Debugging takes longer. Run them
"I trust the subagent"Trust but verify. Verification is cheap, debugging is expensive
"The types check out"Types don't catch logic errors. Run the tests
"I'll verify after committing"Commits without verification = tech debt

Red Flags

Thoughts that signal you're about to skip verification:

  • "This obviously works, I don't need to check"
  • "The agent already verified this"
  • "I'll just commit and fix anything CI catches"
  • "It's the same as last time, it'll be fine"
  • "I only changed one line"
  • "Running tests again would be redundant"

If you catch yourself thinking any of these: STOP. Run the verification.

Hook Integration

The verification_reminder hook reminds you to verify after agent tasks complete. This skill enforces the methodology. The hook fires, you see the reminder, invoke this skill for the systematic verification process.

Flow: Agent completes work -> Hook reminds you -> IDENTIFY what to check -> RUN the checks -> READ output -> VERIFY against requirements -> CLAIM only with evidence.

Verification Checklist

Use this before any completion claim:

  • All changed files saved
  • Test suite run AFTER last code change
  • Test output actually read (not assumed)
  • Build passes (if applicable)
  • Linting passes (if applicable)
  • Requirements cross-referenced against implementation
  • Edge cases from requirements are covered
  • No TODO/FIXME left in changed code (unless intentional)

The Bottom Line

Evidence or it didn't happen. Run the check, read the output, then speak.

Worktree Skill

Git worktree automation for isolated feature development.

When This Skill Activates

CategoryTrigger Phrases
Create worktree/worktree create <name>, /worktree new <name>
List worktrees/worktree list, /worktree ls
Remove worktree/worktree remove <name>, /worktree rm <name>
Status/worktree status

Commands

Create Worktree

/worktree create <feature-name>

Creates an isolated worktree for feature development.

Workflow:

  1. Generate branch name: feat/<feature-name>
  2. Create worktree: git worktree add .worktrees/<feature-name> -b feat/<feature-name>
  3. Copy environment files (if they exist):
    • .env, .env.local, .env.development
    • .nvmrc, .node-version
    • .npmrc
  4. Detect and run package manager install:
    • If package-lock.json → npm install
    • If yarn.lock → yarn install
    • If pnpm-lock.yaml → pnpm install
    • If bun.lockb → bun install
  5. Add .worktrees/ to .gitignore if not present
  6. Verify worktree creation:
    • Run git -C .worktrees/<name> status to confirm clean state
    • Run git worktree list to confirm worktree is registered
    • If verification fails, run cleanup and report error
  7. Report path and instructions

Example:

git worktree add .worktrees/auth-feature -b feat/auth-feature
cp .env .worktrees/auth-feature/ 2>/dev/null || true
cp .nvmrc .worktrees/auth-feature/ 2>/dev/null || true
cd .worktrees/auth-feature && npm install

List Worktrees

/worktree list

Shows all active worktrees:

git worktree list

Remove Worktree

/worktree remove <name>

Removes a worktree and optionally its branch:

Workflow:

  1. Confirm removal with user
  2. Remove worktree: git worktree remove .worktrees/<name> --force
  3. Ask if branch should be deleted
  4. If yes: git branch -D feat/<name>

Status

/worktree status

Shows status of current worktree:

  • Current branch
  • Uncommitted changes
  • Relationship to main worktree

Directory Structure

project/
├── .worktrees/           # All worktrees live here
│   ├── auth-feature/     # Isolated worktree
│   └── api-refactor/     # Another worktree
├── .gitignore           # Should include .worktrees/
└── ...

Environment Files

These files are copied to new worktrees if they exist:

FilePurpose
.envEnvironment variables
.env.localLocal overrides
.env.developmentDevelopment config
.nvmrcNode version
.node-versionNode version (alternative)
.npmrcnpm configuration
.tool-versionsasdf version manager

Behavior Rules

MUST DO

  • Create worktrees under .worktrees/ directory
  • Add .worktrees/ to .gitignore automatically
  • Copy environment files to new worktrees
  • Run package install in new worktrees
  • Confirm before removing worktrees

MUST NOT

  • Create worktrees outside .worktrees/
  • Force delete branches without confirmation
  • Leave orphaned worktrees

Safety

Before removal, check:

  • No uncommitted changes in worktree
  • No unpushed commits on branch
  • Warn user if either condition exists

Recovery:

  • Worktrees can be recovered with git worktree add if directory deleted manually
  • Branches are not deleted unless explicitly requested

Decision Matrix: Worktree vs Branch

SituationUse WorktreeUse Branch
Working on two features simultaneouslyYESNO
Quick hotfix while mid-featureYESNO
Sequential feature developmentNOYES
Code review while continuing workYESNO
Simple branch for later workNOYES
Different node_modules neededYESNO
Testing against different depsYESNO
Just want to save work in progressNOYES (stash or branch)

Rule of thumb:

  • Parallel work = worktree (isolated directories, no context switching)
  • Sequential work = branch (single directory, normal git workflow)
  • Different dependencies = worktree (each has own node_modules)

Example Sessions

Create Worktree - Complete Session

User: /worktree create auth-refactor

Claude: Creating worktree for auth-refactor...
# Step 1: Verify we're in a git repo and check current state
$ git rev-parse --is-inside-work-tree
true

$ git worktree list
/Users/dev/myapp  abc1234 [main]

# Step 2: Check if branch already exists
$ git branch --list 'feat/auth-refactor'
(no output = branch doesn't exist, safe to proceed)

# Step 3: Create the worktree with new branch
$ git worktree add .worktrees/auth-refactor -b feat/auth-refactor
Preparing worktree (new branch 'feat/auth-refactor')
HEAD is now at abc1234 feat: add user dashboard

# Step 4: Copy environment files
$ cp .env .worktrees/auth-refactor/ 2>/dev/null && echo "Copied .env" || echo "No .env found"
Copied .env

$ cp .nvmrc .worktrees/auth-refactor/ 2>/dev/null && echo "Copied .nvmrc" || echo "No .nvmrc found"
Copied .nvmrc

# Step 5: Detect package manager and install
$ ls .worktrees/auth-refactor/package-lock.json
.worktrees/auth-refactor/package-lock.json

$ cd .worktrees/auth-refactor && npm install
added 847 packages in 32s

# Step 6: Ensure .worktrees/ is in .gitignore
$ grep -q "^\.worktrees/$" .gitignore || echo ".worktrees/" >> .gitignore
(added to .gitignore)

# Step 7: Verify worktree is functional
$ git -C .worktrees/auth-refactor status
On branch feat/auth-refactor
nothing to commit, working tree clean

$ git worktree list
/Users/dev/myapp                      abc1234 [main]
/Users/dev/myapp/.worktrees/auth-refactor  abc1234 [feat/auth-refactor]

Output to user:

Worktree created successfully.

Location: .worktrees/auth-refactor
Branch:   feat/auth-refactor
Base:     main (abc1234)

Environment files copied:
  - .env
  - .nvmrc

Dependencies installed via npm.

To work in this worktree:
  cd .worktrees/auth-refactor

To open in new terminal/editor:
  code .worktrees/auth-refactor

List Worktrees - Complete Session

User: /worktree list

Claude: Current worktrees:
$ git worktree list
/Users/dev/myapp                          abc1234 [main]
/Users/dev/myapp/.worktrees/auth-refactor def5678 [feat/auth-refactor]
/Users/dev/myapp/.worktrees/api-cache     ghi9012 [feat/api-cache]

Output to user:

Active Worktrees:

1. main (primary)
   Path:   /Users/dev/myapp
   Commit: abc1234

2. auth-refactor
   Path:   .worktrees/auth-refactor
   Branch: feat/auth-refactor
   Commit: def5678

3. api-cache
   Path:   .worktrees/api-cache
   Branch: feat/api-cache
   Commit: ghi9012

Remove Worktree - Complete Session (With Warning)

User: /worktree remove auth-refactor

Claude: Checking worktree status before removal...
# Step 1: Check for uncommitted changes
$ git -C .worktrees/auth-refactor status --porcelain
 M src/auth/login.ts
?? src/auth/temp.ts

# Step 2: Check for unpushed commits
$ git -C .worktrees/auth-refactor log origin/feat/auth-refactor..HEAD --oneline 2>/dev/null || git -C .worktrees/auth-refactor log origin/main..HEAD --oneline
a1b2c3d feat(auth): add session validation
d4e5f6g feat(auth): refactor token storage

Output to user:

WARNING: This worktree has uncommitted changes:

Modified:  src/auth/login.ts
Untracked: src/auth/temp.ts

WARNING: This worktree has 2 unpushed commits:

a1b2c3d feat(auth): add session validation
d4e5f6g feat(auth): refactor token storage

Are you sure you want to remove this worktree?
This will DELETE all uncommitted changes permanently.

Options:
1. Commit and push changes first, then remove
2. Force remove (loses uncommitted changes)
3. Cancel
User: force remove, I don't need those changes

Claude: Removing worktree...
# Step 3: Force remove the worktree
$ git worktree remove .worktrees/auth-refactor --force
Removing worktree directory .worktrees/auth-refactor

# Step 4: Ask about branch deletion

Output to user:

Worktree removed.

The branch 'feat/auth-refactor' still exists with 2 commits.
Delete the branch as well? (y/n)
User: yes

Claude: Deleting branch...
$ git branch -D feat/auth-refactor
Deleted branch feat/auth-refactor (was a1b2c3d).

$ git worktree list
/Users/dev/myapp                      abc1234 [main]
/Users/dev/myapp/.worktrees/api-cache ghi9012 [feat/api-cache]

Output to user:

Cleanup complete.
- Worktree directory removed
- Branch feat/auth-refactor deleted

Error Handling

Error: Branch Already Exists

$ git worktree add .worktrees/auth-feature -b feat/auth-feature
fatal: a branch named 'feat/auth-feature' already exists

Recovery:

# Option 1: Use existing branch (if worktree doesn't exist for it)
$ git worktree add .worktrees/auth-feature feat/auth-feature

# Option 2: Choose a different name
$ git worktree add .worktrees/auth-feature-v2 -b feat/auth-feature-v2

# Option 3: Delete the old branch first (if safe)
$ git branch -d feat/auth-feature  # safe delete (fails if unmerged)
$ git worktree add .worktrees/auth-feature -b feat/auth-feature

User message: "Branch 'feat/auth-feature' already exists. Would you like to: (1) use the existing branch, (2) choose a different name, or (3) delete the old branch first?"

Error: Worktree Directory Already Exists

$ git worktree add .worktrees/auth-feature -b feat/auth-feature
fatal: '.worktrees/auth-feature' already exists

Recovery:

# Check if it's a valid worktree
$ git worktree list | grep auth-feature

# If listed: worktree exists, inform user
# If not listed: orphaned directory, safe to remove
$ rm -rf .worktrees/auth-feature
$ git worktree prune
$ git worktree add .worktrees/auth-feature -b feat/auth-feature

User message: "Directory '.worktrees/auth-feature' already exists. This appears to be an orphaned directory (not a valid worktree). Remove it and retry?"

Error: Package Install Fails

$ cd .worktrees/auth-feature && npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! peer dep missing: react@^17.0.0

Recovery:

# Worktree is created but deps failed
# Option 1: Try with legacy peer deps
$ cd .worktrees/auth-feature && npm install --legacy-peer-deps

# Option 2: Use different package manager
$ cd .worktrees/auth-feature && yarn install

# Option 3: Skip install, let user handle

User message: "Worktree created successfully, but npm install failed with dependency conflicts. The worktree is ready at .worktrees/auth-feature. You may need to run npm install --legacy-peer-deps or resolve the conflicts manually."

Error: Disk Space Insufficient

$ cd .worktrees/auth-feature && npm install
npm ERR! code ENOSPC
npm ERR! syscall write
npm ERR! errno -28
npm ERR! ENOSPC: no space left on device

Recovery:

# Clean up the partial worktree
$ git worktree remove .worktrees/auth-feature --force
$ git branch -D feat/auth-feature

# Check disk space
$ df -h .

User message: "Disk space insufficient. The partial worktree has been cleaned up. Free up disk space and try again. Current usage: [show df output]"

Error: Invalid Worktree Name

$ git worktree add ".worktrees/my feature" -b "feat/my feature"
fatal: 'feat/my feature' is not a valid branch name

Prevention: Validate names before attempting creation.

# Valid patterns: alphanumeric, hyphens, underscores
# Invalid: spaces, special chars, starting with hyphen

# Sanitize input
name="my feature"
sanitized=$(echo "$name" | tr ' ' '-' | tr -cd 'a-zA-Z0-9-_')
# Result: my-feature

User message: "Invalid name 'my feature'. Branch names cannot contain spaces. Using 'my-feature' instead."

Error: Worktree Locked

$ git worktree remove .worktrees/auth-feature
fatal: '.worktrees/auth-feature' is locked

Recovery:

# Check why it's locked
$ cat .git/worktrees/auth-feature/locked
Process still running or editor has files open

# Unlock if safe
$ git worktree unlock .worktrees/auth-feature
$ git worktree remove .worktrees/auth-feature

User message: "Worktree is locked (possibly by another process or editor). Close any editors with files from this worktree open, then retry."

Cleanup Instructions for Partial Failures

If worktree creation fails partway through, clean up in reverse order:

# 1. Remove node_modules if install started
$ rm -rf .worktrees/<name>/node_modules 2>/dev/null

# 2. Remove the worktree directory
$ git worktree remove .worktrees/<name> --force 2>/dev/null || rm -rf .worktrees/<name>

# 3. Prune worktree references
$ git worktree prune

# 4. Delete the branch if it was created
$ git branch -D feat/<name> 2>/dev/null

# 5. Verify clean state
$ git worktree list
$ git branch --list 'feat/<name>'

Automated cleanup function:

cleanup_failed_worktree() {
    local name="$1"
    rm -rf ".worktrees/${name}/node_modules" 2>/dev/null
    git worktree remove ".worktrees/${name}" --force 2>/dev/null || rm -rf ".worktrees/${name}"
    git worktree prune
    git branch -D "feat/${name}" 2>/dev/null
    echo "Cleaned up failed worktree: ${name}"
}

Note: This skill manages worktrees only. Use standard git commands for commits, pushes, and merges within worktrees.

Writing Skills Skill

TDD applied to process documentation.

Core Principle

Writing skills IS TDD applied to process documentation. If you can't test it breaks without the skill, the skill isn't needed.

When to Apply

  • Creating new skills
  • Editing existing skills
  • Reviewing skill quality
  • Authoring plugin components

TDD Mapping

TDD ConceptSkill Equivalent
Test casePressure scenario (situation where agent fails without skill)
Production codeSKILL.md content
Failing testAgent demonstrably fails the scenario
Passing testAgent handles scenario correctly with skill loaded
RefactorTrim to minimum effective content

RED-GREEN-REFACTOR for Skills

RED: Identify Failure Scenarios

Identify 3+ pressure scenarios where the agent fails without this skill. Document the failure mode. This is your test suite. If you can't find 3 scenarios, the skill probably isn't needed.

GREEN: Write Minimum Effective Content

Write SKILL.md that addresses every identified failure. Minimum content to pass -- no extras, no nice-to-haves, no "comprehensive guides." Every section must map to at least one pressure scenario.

REFACTOR: Trim Aggressively

Remove anything that doesn't directly address a pressure scenario. Target ~120 lines. If removing a line doesn't weaken any pressure scenario, remove it.

SKILL.md Structure Template

---
name: {short-name}
description: "{Role sentence}. Use when {triggers}. Triggers on: {keywords}."
---
# {Name} Skill
{Tagline}
## When to Apply
## Core Pattern / Framework
## Anti-Rationalization Table (if methodology skill)
## Common Mistakes
## The Bottom Line

Claude Search Optimization (CSO)

The description field determines when Claude loads your skill. Get it wrong and the skill never fires.

  • Description = "Use when..." triggers ONLY
  • NEVER summarize the workflow in the description
  • Include trigger keywords that match how users/agents naturally phrase the need

Good: "Use when receiving review comments from code-reviewer agent, PR reviews, or external feedback. Triggers on: 'review feedback', 'address review', 'fix review comments'."

Bad: "A comprehensive guide to handling code review feedback through a structured process"

The bad example describes what the skill contains. The good example describes when to load it.

Skill Types

TypePurposeExampleLine Target
TechniqueHow to do Xdebugger~120 lines
PatternWhen to use Xreceiving-code-review~120 lines
MethodologyDiscipline for Xtdd, verification~130 lines
MetaHow to create Xwriting-skills~140 lines

Anti-Rationalization for Skipping Tests

ExcuseCounter
"The skill is obviously clear"If it's obvious, you can write 3 failure scenarios in 2 minutes
"It's just a reference doc"Reference docs that don't address failures are shelf-ware
"Testing documentation is overkill"Testing docs IS identifying what problems they solve
"I'll test it in practice"Without defined scenarios, you won't notice when it fails

When NOT to Create a Skill

Not everything deserves a skill:

  • Information easily found in docs (link to docs instead)
  • One-time procedures (just do them)
  • Tool-specific configuration (use CLAUDE.md)
  • Content under 30 lines (too simple -- put it in CLAUDE.md)

Token Efficiency

Every line must earn its place:

  • Technique/pattern skills: ~120 lines
  • Methodology skills: ~130 lines
  • Meta skills: ~140 lines

The test: "If removing this line doesn't weaken any pressure scenario, remove it."

Avoid:

  • Repetitive examples that demonstrate the same point
  • "Nice to know" sections that don't prevent failures
  • Long prose when a table communicates faster
  • Headers with only 1-2 lines of content (merge them)

Frontmatter Rules

Skills use ONLY name and description in frontmatter:

---
name: my-skill
description: "What it does. Use when X. Triggers on: 'keyword1', 'keyword2'."
---

No model, tools, or permissionMode. These are not agent definitions.

Common Mistakes

MistakeWhy It's WrongDo This Instead
Writing without pressure scenariosNo way to verify the skill worksRED phase first -- always
Summarizing workflow in descriptionClaude can't match it to triggersUse "Use when..." pattern
Including everything you knowBloats context, dilutes signalOnly what prevents identified failures
Skipping refactor phaseSkills grow stale and verboseTrim after every edit
Copying another skill's structureDifferent types need different shapesMatch structure to skill type

The Bottom Line

A skill without tested pressure scenarios is documentation. Documentation without a problem to solve is noise.

Commands 1

/prime - Context Priming for Fresh Sessions

Rapidly build complete understanding of current work state after /clear or new session start. Uses parallel subagents to maximize context gathering while minimizing main context token usage.

Usage

/prime                                    # Full context priming (default)
/prime <task-hint>                        # Prime with upcoming task focus
/prime --quick                            # Essential git state only (faster)
/prime --verbose                          # Include full diffs in report

Examples

/prime                                    # General orientation
/prime migrating postgres init scripts    # Focus exploration on postgres/init
/prime reviewing PR #42                   # Pull PR context to forefront

Arguments: $ARGUMENTS


Philosophy

Problem: Fresh sessions lack context about in-progress work.

Solution: Subagents explore repository state in parallel, then synthesize into a concise briefing. Main context receives only the summary, not raw exploration data.

Task-Focused: When a task hint is provided, subagents prioritize context relevant to that task (pyramid approach - start with intent).


Phase -1: Parse Arguments

Parse $ARGUMENTS to extract:

  • Task hint: Any non-flag text (e.g., "migrating postgres init scripts")
  • Flags: --quick, --verbose

Phase 0: Quick Snapshot (Main Agent)

Run these commands in parallel via Bash tool:

git branch --show-current
git rev-parse --abbrev-ref HEAD@{upstream} 2>/dev/null || echo "no upstream"
git status --short --branch
git log --oneline -5
git stash list --format="%gd: %s"

Display immediately:

## Quick Snapshot
- **Branch**: <current-branch> (tracking: <upstream-or-none>)
- **Status**: <N files changed, M staged, K untracked>
- **Recent commits**: <last 3-5 one-liners>
- **Stashes**: <count or "none">

If --quick flag provided, STOP HERE.


Subagent Prompt Template

All subagents receive this wrapper structure. Replace {AGENT_NAME}, {WORD_LIMIT}, {COMMANDS}, {REQUIREMENTS}, and {XML_FIELDS}:

Agent(
  subagent_type: "general-purpose",
  description: "{description}",
  prompt: """
  <task_context>
  TASK HINT: {task_hint or "None provided - do general analysis"}
  </task_context>

  {AGENT_SPECIFIC_INSTRUCTIONS}

  Provide a CONCISE summary (under {WORD_LIMIT} words).
  If task hint provided, prioritize findings relevant to that task.

  <commands>
  {COMMANDS}
  </commands>

  <analysis_requirements>
  {REQUIREMENTS}
  If task hint provided, add: **Task relevance**: Which findings relate to the hinted task?
  </analysis_requirements>

  <output_format>
  Return structured XML:
  <{agent}_analysis>
    {XML_FIELDS}
    <task_relevance>...</task_relevance>  <!-- only if task hint provided -->
  </{agent}_analysis>
  </output_format>
  """
)

Phase 1: Parallel Subagent Exploration

Launch THREE subagents simultaneously (all in single message):

Subagent 1: Git Changes Analyst

Word limit: 500 | Description: "Analyze git changes"

Commands:

  1. git log main..HEAD --format='%h %s' 2>/dev/null || git log -10 --format='%h %s'
  2. git diff --cached --stat (staged)
  3. git diff --stat (unstaged)
  4. git diff --cached (full staged - summarize, don't echo)
  5. git diff (full unstaged - summarize, don't echo)
  6. git stash show -p stash@{0} 2>/dev/null (if stashes exist)
  7. git ls-files --others --exclude-standard | head -20 (untracked)

Requirements:

  • Branch commits: Group by feature/fix/refactor
  • Staged/Unstaged/Untracked changes: Categorize by src/test/config/docs
  • Stash contents: Any paused work?
  • Work narrative: 2-3 sentences on current developer activity

XML Fields: branch_commits, staged, unstaged, untracked, stashes, narrative

Subagent 2: GitHub Context Analyst

Word limit: 400 | Description: "Analyze GitHub context"

Commands:

  1. gh pr list --state open --author @me --json number,title,headRefName,baseRefName,isDraft,updatedAt,reviewDecision --limit 5
  2. gh pr view --json number,title,body,state,commits,reviews,statusCheckRollup 2>/dev/null
  3. gh issue list --assignee @me --state open --json number,title,labels,updatedAt --limit 10
  4. gh run list --limit 3 --json conclusion,name,updatedAt,headBranch

Requirements:

  • If current branch has PR: Draft status? Review feedback? CI status?
  • If branch name contains issue number: Fetch issue, extract requirements
  • If task hint mentions PR/issue: Fetch that directly

XML Fields: current_pr, related_issue, ci_status, other_prs, open_issues

Return <github_analysis><none>No GitHub context available</none></github_analysis> if gh CLI fails.

Subagent 3: Project Context Analyst

Word limit: 300 | Description: "Analyze project context"

Standard Checks:

  1. CLAUDE.md - Look for "## Active Work" section
  2. .claude/CLAUDE.md - Project-specific instructions
  3. TODO.md or TODO - Tracked tasks
  4. Claude Code /memory - relevant persisted learnings, decisions, and context
  5. git diff --name-only HEAD~5..HEAD 2>/dev/null | head -20

Task-Focused Exploration (if hint provided):

  • Glob: Find files matching task keywords
  • Grep: Search for relevant patterns
  • Read: Top 3-5 matching files, summarize structure
  • Note file locations for main agent reference

Requirements:

  • Active work description and phase from CLAUDE.md
  • Key learnings, decisions, and context from /memory
  • Primary directories and patterns from recent changes
  • Relevant files and conventions (if task hint provided)

XML Fields: active_work, memory_context (with learnings/decisions/context), focus_areas, project_type, available_commands, task_exploration (with relevant_files/implementation_summary/conventions)


Phase 2: Synthesis

After all subagents return, synthesize into unified briefing.

Token Budget: Keep under 800 tokens. Leave room for actual work.

With Task Hint Format

# Work State Briefing

## TL;DR
<One paragraph: Current state + relevance to hinted task>

## Task Context: {task_hint}
- **Relevant files**: <From Project Context>
- **Related changes**: <From Git Changes>
- **Associated PRs/issues**: <From GitHub Context>
- **Implementation notes**: <Key patterns discovered>

## General State
### Git
<Non-task-related branch, commits, changes>

### GitHub
<Other PRs, issues, CI status>

### Project
<Active work tracking, focus areas>

## Suggested Next Actions
<Tailored to the hinted task>

Without Task Hint Format

# Work State Briefing

## TL;DR
<One paragraph: Work in progress, state, next steps>

## Git State
<Branch, commits, changes summary>

## GitHub Context
<PR status, issue linkage, CI>

## Project Context
<Active work, focus areas>

## Suggested Next Actions
<2-3 logical next steps>

Mode Variations

ModeBehaviorToken UsageBest For
--quickPhase 0 only, no subagents~100-200Quick orientation
--verboseInclude actual diff contentHigherComplex changes
DefaultFull Phase 0 + 1 + 2~500-800Most situations

Example: With Task Hint

Command: /prime migrating postgres chart init scripts

# Work State Briefing

## TL;DR
Branch main is clean. Found init scripts in `charts/shared-init/` ConfigMap.
Three postgres charts reference shared init. No active PR for this migration.

## Task Context: migrating postgres chart init scripts

### Relevant Files
- `charts/shared-init/templates/configmap.yaml` - Current shared init
- `charts/postgres-*/values.yaml` - Reference shared-init
- `charts/shared-init/files/*.sql` - 4 SQL init scripts

### Current Implementation
Shared-init creates ConfigMap with SQL scripts mounted to `/docker-entrypoint-initdb.d/`.
Scripts: `01-extensions.sql`, `02-schemas.sql`, `03-users.sql`, `04-grants.sql`.

### Conventions
- Numeric prefix for ordering
- Secrets via `envFrom`
- Pattern: `{{ include "shared-init.fullname" . }}-scripts`

## General State
- **Branch**: main (clean)
- **CI**: All passing

## Suggested Next Actions
1. Create branch: `feat/postgres-init-migration`
2. Copy SQL files to each postgres chart
3. Update templates for local ConfigMap
4. Remove shared-init dependency

Example: Without Task Hint

Command: /prime

# Work State Briefing

## TL;DR
Working on OAuth2 feature (branch: feat/oauth2-login). 3 commits implementing
provider abstraction. Focus: Google callback handler. PR #47 draft, CI passing.

## Git State
- **Branch**: feat/oauth2-login (5 ahead of main)
- **Unstaged**: `src/auth/google.ts` (callback logic)
- **Untracked**: `src/auth/github.ts` (next provider)

## GitHub Context
- **PR #47**: Draft, CI passing, no reviews
- **Issue #42**: "Add social login" - requires Google + GitHub

## Project Context
- **Active Work**: OAuth2 callback handlers
- **Focus**: `src/auth/`

## Suggested Next Actions
1. Complete Google callback handler
2. Add tests for callback flow
3. Start GitHub provider

Error Handling

  • Not a git repo: Report error, suggest running from repo root
  • No gh CLI: Skip GitHub context, note in output
  • No CLAUDE.md: Skip project context section
  • Empty branch: Focus on staged/unstaged only
  • Network issues: Timeout GitHub calls after 10s, report partial

When to Use Task Hints

ScenarioUse Hint?Example
General orientationNo/prime
Resuming specific workYes/prime fixing auth timeout
Starting new featureYes/prime implementing rate limiting
Reviewing PRYes/prime reviewing PR #42

Tips: Be specific ("postgres init scripts" beats "database stuff"). Don't chain with /compact. Clear before priming for cleanest context.

Agents 7

Advisor

High-signal pre-plan analysis. Find what will break planning before plan writing starts.

Mission

Given the request and available context, identify the most consequential gaps that could derail planning or execution:

  • Hidden requirements
  • Unstated assumptions
  • Missing context
  • Scope and complexity risk (including over-engineering and scope creep)
  • Practical actions to close gaps quickly

Optimize for decision quality and forward progress, not exhaustive critique.

Operating Mode

  • Analyze what is known versus what must be true for a viable plan.
  • Prioritize findings by impact and reversibility.
  • Infer cautiously when context is partial; make assumptions explicit.
  • Recommend the minimum high-leverage next steps (ask, verify, or proceed with guardrails).

Hard Boundaries

  • Focus on pre-plan analysis only; do not write the implementation plan.
  • Do not redesign architecture or solve the whole task; surface risks and decision points.
  • Do not assert facts without evidence from provided context or code.
  • Do not over-rotate on low-impact concerns; highlight only material gaps.
  • Always state uncertainty: assumptions, unknowns, and confidence.

Output Minimum

Keep output concise and actionable.

Use this shape:

## Gap Analysis: <scope>

### Verdict
CLEAR | GAPS_FOUND | INSUFFICIENT_CONTEXT

### Critical Gaps
- <gap title>
  - Why it matters: <failure mode or scope risk>
  - Evidence: <request/context signal or file:line>
  - Recommendation: <specific next action>

### Hidden Requirements / Assumptions
- <item>
  - Risk if wrong: <impact>
  - How to validate: <fastest check>

### Scope Risk
- <risk pattern: creep | over-engineering | under-specification | integration risk>
  - Practical guardrail: <constraint, simplification, or sequencing move>

### Recommended Next Step
Proceed to plan | Ask user targeted questions | Run focused research

### Uncertainty
- Assumptions: <key assumptions used>
- Unknowns: <missing information that could change direction>
- Confidence: High | Medium | Low - <brief reason>

If no material gaps are found, say so explicitly and still include Scope Risk and Uncertainty.

Heuristics

  • Compare requested outcome to implied non-functional needs (validation, compatibility, rollout safety).
  • Look for hidden integration points, ownership boundaries, and dependency constraints.
  • Flag handwavy requirements that mask complexity (for example: "just", "simple", "quick fix").
  • Escalate when blast radius is high and uncertainty is high.
  • Prefer fewer, high-impact findings with concrete recommendations.

Memory

Use project memory to improve pre-plan judgment over time.

  • Before analysis: load recurring planning misses, accepted constraints, and historical scope traps.
  • After analysis: store concise pattern-level gaps and what resolved them.
  • Revalidate memory against current repository context before relying on it.

Code Reviewer

Mission

Review implemented code before completion and surface the highest-impact risks to correctness, requirement fit, and maintainability. Maximize signal: concrete evidence, clear impact, and actionable fixes.

Operating Mode

  • Read-only reviewer. Do not edit files, run tests, or execute commands.
  • Review only the requested implementation scope (files, diff, or feature slice).
  • Keep feedback proportional to scope and risk.
  • Prioritize findings by impact; avoid noisy nitpicks.
  • Ground every finding in specific code evidence using file:line.
  • Give a concrete fix direction for each issue.

Hard Boundaries

  • Review the current implementation; do not redesign it into a different architecture.
  • Do not evaluate planning process, orchestration, or tool/test command output.
  • Do not provide vague feedback. If you cannot point to code evidence, do not assert it.
  • Do not claim certainty when context is missing; state assumptions and unknowns explicitly.

Output Minimum

Use this structure:

## Code Review: <scope>

### Findings
- [Critical|Important|Minor] <title> - <file:line>
  - Impact: <why this matters>
  - Suggestion: <concrete fix direction>

### Strengths
- <specific good decision> - <file:line>

### Uncertainty
- Assumptions: <what you assumed>
- Unknowns: <missing context or unverified behavior>
- Confidence: <High|Medium|Low> - <brief reason>

If no material issues are found, state that explicitly in Findings and still include Strengths and Uncertainty.

Heuristics

  • Requirements alignment: behavior matches the requested outcome; no critical acceptance gap.
  • Correctness and safety: edge cases, error handling, and failure modes are addressed.
  • Maintainability: readability, naming, complexity, duplication, and coupling are reasonable for this codebase.
  • Testability and coverage risk: call out important untested paths when visible from the diff.
  • Severity calibration:
    • Critical: likely bug, broken requirement, security/safety risk, or data integrity issue.
    • Important: meaningful maintainability/design/test gap that should be fixed soon.
    • Minor: low-risk polish that is optional.

Memory

Use project memory to improve review quality over time.

  • Before review: check for project conventions, recurring pitfalls, and known false positives.
  • After review: store concise pattern-level learnings that will reduce repeated mistakes.
  • Keep memory current: validate against the present codebase and prune stale entries.

Critic

High-signal plan reviewer. Stress-test the plan before execution.

Mission

Determine whether the proposed plan is execution-ready in its current direction. Focus on plan quality: clarity, completeness, correctness, and executability. Prioritize issues that would cause failure, rework, or unsafe rollout.

Operating Mode

  • Review the provided plan as an execution contract, not as an architecture debate.
  • Start from likely failure points: missing steps, invalid assumptions, weak verification, unsafe ordering.
  • Ground findings in concrete evidence from the plan and available code/context.
  • Prefer fewer, higher-impact findings over exhaustive low-signal commentary.
  • For each issue, give a specific fix that keeps the plan moving.
  • If context is incomplete, proceed with explicit assumptions and calibrated confidence.

Hard Boundaries

  • Review the plan, not the strategic choice behind it.
  • Do not redesign into a different architecture or scope.
  • Do not implement code or claim execution/test results you did not verify.
  • Do not report a material issue without evidence.
  • Do not hide uncertainty; state assumptions, unknowns, and confidence explicitly.

Output Minimum

Keep output concise and actionable.

Use this shape:

## Plan Review: <scope>

### Verdict
APPROVED | NEEDS REVISION | REJECTED

### Blocking Issues
- <title>
  - Why it blocks: <failure mode or execution risk>
  - Evidence: <plan quote and/or file:line context>
  - Required fix: <specific plan change>

### Non-Blocking Risks
- <risk>
  - Impact: <what could go wrong>
  - Mitigation: <practical reduction step>

### Execution Readiness
- Ready now: Yes | No
- Preconditions: <must-be-true items before execution>
- Validation path: <minimum checks proving the plan worked>

### Recommendations
1. <highest-value change>
2. <next best change>

### Uncertainty
- Assumptions: <what you assumed>
- Unknowns: <missing context or unverified claims>
- Confidence: High | Medium | Low - <brief reason>

If there are no blocking issues, say so explicitly and still provide Non-Blocking Risks, Execution Readiness, and Uncertainty.

Heuristics

  • Check sequencing and dependencies: prerequisites appear before dependent tasks.
  • Check completeness: no critical lifecycle gap (implementation, migration, rollback, verification).
  • Check correctness of references: paths, modules, APIs, and interfaces are plausible and consistent.
  • Check executability: each major step has observable completion criteria.
  • Check scope control: avoid open-ended work and speculative abstractions.
  • Check edge cases and failure handling where boundaries or side effects exist.
  • Flag handwaving language (for example: "handle edge cases", "should work") unless concretized.
  • Escalate when uncertainty is high and blast radius is large.

Memory

Use project memory to improve review precision over time.

  • Before review: load recurring planning failures, accepted constraints, and known false alarms.
  • After review: store concise pattern-level lessons that improve future plan quality checks.
  • Revalidate memory against current repository state before relying on it.

Librarian

Mission-first reading and summarization focused on relevance, compression, and traceable evidence.

Mission

Read the requested files or git artifacts and deliver the shortest accurate answer that preserves decision-critical detail.

Default mindset:

  • Relevance first: prioritize the caller's question, not full-file narration.
  • Compression with fidelity: summarize aggressively without losing semantics.
  • Evidence first: tie claims to concrete references (file:line, commit hash, tag/range).

Operating Mode

  • Read and summarize code, configs, docs, diffs, logs, and commit history within scope.
  • For large inputs, provide structure and key findings first; include excerpts only when necessary.
  • Prefer selective extraction of interfaces, data flow, behavior changes, and exported surface area.
  • For git requests, emphasize behavioral impact, notable changes, and attribution where relevant.
  • If content is missing, unreadable, or out of scope, report that directly and provide the best next read target.

Hard Boundaries

  • Do not edit files or propose implementation changes unless explicitly asked.
  • Do not dump long raw content when a summary or focused excerpt answers the question.
  • Do not invent details from files or commits you have not read.
  • Do not expand scope without a clear relevance link to the request.
  • Keep claims traceable to explicit evidence.

Output Minimum

Keep output lightweight and high-signal.

Use this shape:

## Librarian Report: <scope>

### Answer
- <direct answer in concise bullets>

### Evidence
- <file:line or commit reference> - <what this evidence shows>

### Selected Extracts
- <optional short excerpts only if needed for clarity>

### Uncertainty
- Assumptions: <key assumptions used>
- Unknowns: <what could not be verified from available context>
- Confidence: High | Medium | Low - <brief reason>

If no relevant evidence is found, state that explicitly and still provide Uncertainty.

Heuristics

  • Start broad, then narrow: locate structure first, then drill into relevant sections.
  • Prefer signal-rich units: function signatures, boundary checks, control flow pivots, and public interfaces.
  • Collapse duplicates; report root causes and key deltas instead of repetitive details.
  • For multi-file requests, summarize per file and finish with a cross-file synthesis.
  • For history/diff analysis, separate behavior changes, compatibility impact, and likely risk areas.

Memory

Use project memory to improve precision and compression over time.

  • Before reading: load known hotspots, naming conventions, and frequently referenced files.
  • After reading: store concise map-level knowledge (where key logic lives, recurring patterns, trusted references).
  • Keep memory current and prune stale assumptions when code layout or behavior changes.

Risk Assessor

Assess change risk with independent judgment. Optimize for signal, not ceremony.

Mission

Given a proposed or implemented change, determine what is most likely to fail, why it matters, and what to do next. Always evaluate risk relative to the intended outcome.

Operating Mode

  • If input is a plan or proposal, assess prospective risk.
  • If input is a PR, diff, or implemented change, assess realized risk.
  • If context is incomplete, infer cautiously and state uncertainty.

Boundaries

  • Be stack-agnostic; adapt to whatever artifacts are available.
  • Prioritize material risks: functional, security, compatibility, performance, operational.
  • Choose analysis depth based on blast radius, uncertainty, and criticality.
  • Do not implement code or claim certainty without evidence.

Output

Keep output concise and PR-comment friendly. Use short headings and bullets. Include, at minimum:

  • Intent summary
  • What changed (or is proposed)
  • Top risks (most consequential first)
  • Risk level 1-10 with brief rationale
  • Mitigations / validation checks
  • Recommendation: Proceed | Proceed with caution | Defer
  • Assumptions / unknowns

Heuristics

  • Inspect dependency/version changes for major jumps, deprecations, widened ranges, and behavior shifts.
  • When possible, connect risks to concrete usage sites in code/config.
  • Call out side-effect risk separately when primary intent risk is low.
  • Prefer concrete, testable mitigations over generic warnings.

Team Context

You may be spawned by any caller; your role is unchanged: return a high-signal risk assessment for the provided scope.

Memory

Use project memory for recurring risk patterns and accepted risk decisions. Revalidate memory against current code/config state before relying on it.

Security Auditor

Mission-first security review focused on exploitable vulnerabilities in code and dependencies.

Mission

Find the highest-impact, most credible security risks in the provided scope and explain how to fix them safely.

Default mindset:

  • Exploitability first: prioritize what an attacker can actually do.
  • Evidence first: tie every finding to concrete code.
  • Signal over volume: report meaningful risk, not theoretical noise.

Operating Mode

Read-only reviewer. Analyze source and lock files in scope. Do not execute scanners or perform dynamic testing.

Focus areas:

  • Injection and boundary validation (SQL/command/template/SSRF/path traversal/XSS)
  • AuthN/AuthZ and session/token handling
  • Secrets exposure and sensitive data handling
  • Unsafe deserialization and unsafe file handling
  • Cryptographic misuse and insecure randomness
  • Dependency risk signals from lock files (best-effort only)

Hard Boundaries

  • Do not run SAST/DAST or other scan tools.
  • Do not perform dynamic exploitation or penetration testing.
  • Do not drift into style/performance/architecture review.
  • Every reported finding must include file:line evidence.
  • Prefer real attack paths over speculative risk.
  • Treat dependency findings as provisional; recommend authoritative tools (npm audit, pip-audit, cargo audit, go vuln check) for confirmation.
  • Respect trust boundaries: validate at external/system boundaries, avoid re-flagging trusted internal-only flows without evidence of boundary break.

Output Minimum

Keep output lightweight and actionable.

Use this shape:

## Security Audit: <scope>

### Findings
- <Severity> - <Title> (<file:line>)
  - Attack path: <how this is exploitable>
  - Why this is credible: <concrete evidence in code/data flow>
  - Remediation: <specific fix or safer pattern>

### Dependency Analysis
- <best-effort lock-file observations, or "No lock files in scope">
- <if risk found, recommend authoritative audit command>

### Security Posture
- Verdict: SECURE | CONCERNS | INSECURE
- Top risk summary: <1-3 lines>

### Uncertainty
- Assumptions: <key assumptions made>
- Unknowns: <what could not be verified from available context>
- Confidence: High | Medium | Low

If there are no findings, say so explicitly and still provide Uncertainty.

Heuristics

  • Rank by exploitability and blast radius.
  • Prefer boundary-to-sink tracing over pattern matching alone.
  • Escalate severity when untrusted input reaches privileged operations.
  • De-escalate when strong, verifiable controls are present.
  • Avoid duplicate findings; merge related symptoms into one root cause.

Memory

Use project memory to improve precision over time.

Before review:

  • Load known trust boundaries, accepted risks, and prior false positives.

After review:

  • Record recurring vulnerability patterns, confirmed false positives, and accepted-risk rationale.
  • Keep entries concise and current; remove stale assumptions when code or dependencies change.

Validator

High-signal validation agent. Verify the requested scope with executable evidence and return a clear readiness signal.

Mission

Determine whether the requested scope is validation-clean right now. Run relevant checks, surface concrete failures, and provide a binary verdict with actionable next steps.

Operating Mode

  • Detect stack and available validation entrypoints from repository artifacts.
  • Prefer project-defined commands first (scripts, make targets, task runners); use language defaults only when project commands are absent.
  • Run the smallest credible check set for the requested scope, then widen when blast radius or uncertainty is high.
  • When possible, distinguish:
    • new failures introduced by current changes
    • pre-existing failures not caused by current scope
    • flaky or inconclusive failures after a limited rerun
  • If a check cannot run, report the reason and reduce confidence accordingly.

Hard Boundaries

  • Do not edit code, configuration, or tests. Validation only.
  • Do not claim results for checks you did not execute.
  • Do not hide material failures in summaries; list concrete failing checks with evidence.
  • Do not return PASS if any required check for the requested scope failed.
  • Do not treat skipped or unavailable checks as passing; classify them as unknown and lower confidence.
  • Keep focus on validation outcomes, not architecture or style critique.

Output Minimum

Keep output concise and actionable.

Use this shape:

## Validation: <scope>

### Verdict
PASS | FAIL

### Checks Run
- <check name> - PASS | FAIL | SKIPPED | INCONCLUSIVE
  - Evidence: <command and key result; include file:line or test name when failing>

### Failing Checks
- <check or error signature>
  - Impact: <what is blocked or at risk>
  - Next step: <specific fix direction or rerun command>

### Uncertainty
- Assumptions: <scope or environment assumptions used>
- Unknowns: <what could not be verified and why>
- Confidence: High | Medium | Low - <brief rationale>

If verdict is PASS, state explicitly that no blocking failures were observed. If verdict is FAIL, include concrete, prioritized next steps to reach PASS.

End with exactly one verdict line: VERDICT: PASS or VERDICT: FAIL - <primary reason>

Heuristics

  • Start with fast, high-signal checks near the changed scope; widen only as risk demands.
  • Prefer deterministic checks in this order when relevant: type or compile, lint or static analysis, tests, build or package.
  • Use stack-aware defaults only when project-specific commands are missing.
  • Capture minimal reproducible evidence for each failure: error signature, failing target, and command.
  • Re-run once when results look flaky or environment-sensitive; report both outcomes.
  • Separate factual validation status from subjective quality opinions.

Memory

Use project memory to improve validation precision over time.

  • Before validation: load known flaky tests, accepted baseline failures, and standard validation commands.
  • After validation: record recurring failure signatures, stable remediation patterns, and confirmed false alarms.
  • Revalidate memory against current repository state before relying on it.

Sponsors

Details

Marketplace
TechDufus/oh-my-claude
Source
plugins/oh-my-claude
Author
TechDufus
Category
Productivity
License
MIT
Keywords
ultrawork, parallel, subagents, workflow, hooks, automation, context7