Core ACE workflow with structured skills, task enforcement, and quality reviewers

version
13.1.1
GitHub stars
16

Install

/plugin install rcc@rcc

Run it inside Claude Code after adding the marketplace with /plugin marketplace add wayne930242/Reflexive-Claude-Code.

Contents

Discovered from source

Skills 23

Advising Architecture

Overview

Advising architecture IS classifying knowledge into the correct Claude Code component.

One concept, one location. Misclassification wastes tokens (global rule that should be scoped) or misses enforcement (advisory instruction that should be a deterministic hook).

Core principle: CLAUDE.md = broad project instructions. Rules = path-scoped conventions. Skills = on-demand capabilities. Agents = isolated workers. Hooks = deterministic enforcement.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Understand the request
  2. Scan for conflicts
  3. Classify component type
  4. Provide recommendation

Announce: "Created 4 tasks. Starting execution..."

Component Hierarchy (Priority Order)

1. CLAUDE.md (highest)       - Broad project instructions
   └─ Loaded every session (expensive — keep < 200 lines)
   └─ Only what Claude can't figure out from code
   └─ Specific, verifiable instructions with MUST/NEVER emphasis

2. Rules (.claude/rules/)    - Path-scoped conventions
   └─ Loaded only when Claude reads a file matching paths:
   └─ No paths = loaded at launch, every session
   └─ < 50 lines each (token cost)
   └─ Frontmatter: paths (YAML array of globs)

3. Skills (.claude/skills/)  - Capabilities (how to do)
   └─ Loaded on-demand by Claude OR invoked via /skill-name
   └─ Progressive disclosure: SKILL.md + references/
   └─ Gerund naming: writing-skills, not write-skill
   └─ Frontmatter: name, description, when_to_use,
      argument-hint, arguments, allowed-tools,
      disallowed-tools, model, effort, context, agent,
      background, hooks, paths, shell, user-invocable,
      disable-model-invocation

4. Agents (.claude/agents/)  - Isolated context workers
   └─ Invoked via Agent tool
   └─ Frontmatter: name, description, tools,
      disallowedTools, model, maxTurns, skills,
      permissionMode, effort, isolation, background,
      memory, mcpServers, hooks, color, initialPrompt
   └─ context/agent are SKILL fields — invalid here

5. Hooks (.claude/hooks/)    - Automated quality gates
   └─ Exit code 2 = block action
   └─ < 5 seconds execution
   └─ Static checks only

Classification Decision Tree

Does it apply BROADLY to all project work?
├─ Yes → CLAUDE.md instruction
│   Examples: Communication style, build commands, architecture
│   Key: Keep < 200 lines, specific and verifiable
│
└─ No → What type of knowledge?
    │
    ├─ HOW TO DO something (capability)?
    │   → SKILL in skills/
    │   Naming: gerund form (writing-*, creating-*)
    │   Structure: Overview → Routing → Tasks (+ Red Flags / Task Initialization as needed)
    │   Routing pattern:
    │     ├─ Contains decision points → Tree
    │     ├─ Part of multi-skill workflow → Chain
    │     ├─ Simple, single task → Node (context: fork, model: haiku)
    │     └─ Internal steps only → Skill Steps
    │   Consider: context: fork for analysis-oriented skills
    │   Consider: model selection (haiku for fast, opus for complex)
    │
    ├─ WHAT TO DO (convention for specific files)?
    │   → RULE in .claude/rules/
    │   Use when: different paths need different conventions
    │     e.g., monorepo packages with different frameworks,
    │     src/ vs tests/ with different coding standards,
    │     frontend (React) vs backend (Express) rules
    │   paths: glob isolates rules to matching files only
    │   Format: paths as YAML array of globs
    │   Keep < 50 lines, imperative language
    │
    ├─ ISOLATED WORKER (needs separate context)?
    │   First consider: built-in subagent types (Explore, Plan, general-purpose)
    │   Then consider: skill with context: fork
    │   Last resort: custom AGENT in agents/
    │   CRITICAL: isolated context = no conversation history
    │   → Design argument-hint/prompt to pass sufficient context
    │
    └─ AUTOMATED CHECK (quality gate)?
        → HOOK in .claude/hooks/
        Python script, exit 2 to block
        Configure in settings.json

Best Practices per Component

CLAUDE.md

  • < 200 lines — loaded every session; only what Claude can't figure out from code
  • Specific and verifiable; use MUST/NEVER sparingly
  • NOT for: linter-enforceable rules (hooks), path-scoped (rules), workflows (skills)

Rules (.claude/rules/)

  • < 50 lines each; use paths: YAML array to scope to file patterns
  • Imperative language; best for monorepo/frontend-vs-backend conventions
  • NOT for: procedures (skills), broad instructions (CLAUDE.md)

Skills (.claude/skills/)

  • On-demand loading = token efficient; use context: fork for analysis tasks
  • Use model to optimize cost; disable-model-invocation: true for manual-only
  • NOT for: conventions (rules), broad instructions (CLAUDE.md)

Agents (.claude/agents/)

  • First consider built-in types (Explore/Plan/general-purpose), then context: fork
  • Tools declared upfront — subagents CANNOT request at runtime
  • NOT for: guidance (skills), conventions (rules)

See references/model-selection.md for agent three-layer model selection guide.

Hooks (.claude/hooks/)

  • Deterministic enforcement; exit code 2 = block; keep < 5 seconds
  • Best for: lint checks, format validation, commit message enforcement
  • NOT for: complex workflows (skills), advisory guidelines (CLAUDE.md/rules)

Task 1: Understand the Request

Goal: Clarify what is being created or modified.

Questions to answer:

  • What knowledge is being encoded?
  • Does it apply broadly to all project work, or only to specific paths?
  • Does it teach a capability (how to) or enforce a convention (what to)?
  • Does it need deterministic enforcement (hook) or advisory guidance (CLAUDE.md/rule)?

Verification: Can state the knowledge type in one sentence.

Task 2: Scan for Conflicts

Goal: Check existing components for overlaps.

Process:

  1. Check CLAUDE.md for related instructions
  2. Check .claude/rules/ for overlapping conventions
  3. Check skills/ for duplicate capabilities
  4. Check agents/ for overlapping responsibilities

Verification: Listed all related existing components (or confirmed none).

Task 3: Classify Component Type

Goal: Apply decision tree to determine correct component type.

If it...Then it's a...
Applies broadly to all project workCLAUDE.md instruction
Different paths need different conventions (monorepo, frontend vs backend)RULE with paths:
Teaches how to do somethingSKILL
Needs isolated execution contextAGENT (or skill with context: fork)
Is an automated quality gateHOOK

Verification: Classification matches decision tree logic.

Task 4: Provide Recommendation

Goal: Deliver structured recommendation.

Output format:

## Architecture Assessment

**Request:** [What you're trying to create]

**Classification:** [CLAUDE.md / rule / skill / agent / hook]

**Rationale:** [Why this classification]

**Location:** [Exact path where it should go]

**Conflicts Found:**
- [List any existing components that overlap, or "None"]

**Key Constraints:**
- [Important rules for this component type]

**Recommendation:** [Proceed / Reconsider / Merge with existing]

Verification: Recommendation includes all fields above.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "This is both a rule AND a skill"
  • "CLAUDE.md is overkill, a rule is fine"
  • "Global rule is fine without paths:"
  • "Skip conflict scan, it's obviously new"
  • "Agent is needed" (before considering built-in types or context: fork)

All of these mean: You're about to misclassify. Follow the decision tree.

Common Rationalizations

ExcuseReality
"It's a bit of both"Every knowledge has ONE correct location. Classify precisely.
"CLAUDE.md is too heavy"If it applies broadly, it belongs in CLAUDE.md. If it must be enforced, use a hook.
"Global rule is simpler"Global = always injected = token cost. Scope it.
"Need a custom agent"Built-in types or context: fork often suffice.
"Conflict scan is overkill"Duplicated knowledge = contradictions. Always scan.

Analyzing Agent Systems

Overview

Analyzing agent systems IS understanding the project context, detecting weaknesses, and producing actionable restructuring recommendations.

Scan the project structure, inventory every agent component (CLAUDE.md, rules, hooks, skills, agents), check against 11 weakness categories, generate restructuring recommendations, and produce a severity-rated report.

Core principle: Analyze the project first, then the agent system. Recommendations without project context are guesses.

Routing

Pattern: Chain Handoff: user-confirmation Next: planning-agent-systems (if recommendations are clear) or brainstorming-workflows (if more exploration needed) Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Scan project structure
  2. Scan agent components
  3. Run weakness analysis
  4. Produce restructuring recommendations
  5. Produce analysis report
  6. Present findings to user

Announce: "Created 6 tasks. Starting execution..."

Task 1: Scan Project Structure

Goal: Understand the project before analyzing its agent system.

Important: Read references/project-scanning.md for the full scanning guide.

Scan areas:

  • Language and framework detection (package.json, Cargo.toml, go.mod, pyproject.toml, etc.)
  • Project type inference (monorepo, library, application, CLI tool, etc.)
  • Dev workflow detection (CI/CD configs, Makefile, scripts/, etc.)
  • Team scale signals (CODEOWNERS, contributing guides, PR templates, branch protection)

Record findings in Project Overview format:

  • Primary language(s) and framework(s)
  • Project type and structure
  • Build and test tooling
  • Dev workflow and CI/CD
  • Team size signals
  • Notable conventions or constraints

Verification: Project overview complete with all aspects filled.

Task 2: Scan Agent Components

Goal: Find all agent system components in the project.

Scan locations:

  • CLAUDE.md (project root and .claude/)
  • .claude/rules/**/*.md
  • .claude/settings.json (hooks section)
  • .claude/skills/ or plugin skill directories
  • .claude/agents/ or subagent definitions
  • ~/.claude/rules/ (user-level rules)
  • ~/.claude/CLAUDE.md (user-level constitution)
  • ~/.claude/skills/ (user-level skills)
  • .cursorrules, .github/copilot-instructions.md, .windsurfrules (other AI tool configs)
  • .editorconfig, linter configs (conventions that should be mirrored)

For each component found, record:

  • Type (CLAUDE.md / rule / hook / skill / agent)
  • Scope (user-root / project)
  • Path
  • Line count
  • Brief purpose (from frontmatter or first heading)

User-root gap analysis: Compare ~/.claude/rules/ against .claude/rules/:

  • Which user-root rules have no project-level specialization?
  • Which languages/frameworks are used in the project but have no matching rules or hooks?
  • Does the project have a settings.local.json for sensitive data?

Verification: Complete inventory of all components with paths, types, and scope. Gap analysis between user-root and project level documented.

Task 3: Run Weakness Analysis

Goal: Check every component against the 11-category weakness checklist.

Important: Read references/weakness-checklist.md for the full 11-category checklist.

For each weakness found, record:

  • Category (1-11)
  • Severity: CRITICAL / WARNING / INFO
  • Component affected
  • Specific finding (what's wrong)
  • Suggested fix (one sentence)

Severity guidelines:

SeverityCriteria
CRITICALBlocks normal operation, causes errors, security risk
WARNINGDegrades experience, causes confusion, maintenance burden
INFOMinor improvement, cosmetic, nice-to-have

Cross-component checks:

  • Compare all skill descriptions for overlap
  • Check CLAUDE.md content against rules for duplication
  • Check hook coverage against rule requirements
  • Verify skill chain connections are complete

Pipeline checks:

  • Scan all skill handoff definitions, build skill call graph
  • Detect chain breaks: skill A hands off to B, but B doesn't exist or doesn't accept A's output
  • Detect orphan nodes: skill with no inbound handoffs and not an entry point
  • Detect dead ends: skill with no handoff and no explicit termination
  • Check state persistence: does each pipeline have state files/directory for recoverability?
  • Classify pipeline mode: owner-pipe vs chain-pipe, check for mode mismatch

Verification: Every checklist item evaluated. At least one pass through each category. Pipeline checks complete.

Task 4: Produce Restructuring Recommendations

Goal: Transform weakness findings and project overview into actionable recommendations.

Important: Read references/restructuring-guide.md for the full recommendation guide.

Generate recommendations by type:

Merge recommendations:

  • Overlapping skills that should be consolidated
  • Redundant rules covering the same concern
  • Duplicate content across CLAUDE.md and rules

Extract recommendations:

  • CLAUDE.md sections that should be extracted to rules (scoped or global)
  • Monolithic rules that should be split by concern

Pipeline recommendations:

  • Pipeline design based on project type (monorepo vs single-app vs library)
  • Pipeline mode selection (owner-pipe vs chain-pipe) with rationale
  • State persistence strategy for recoverability

Traceability requirement: Every recommendation must trace to a specific weakness finding or project characteristic. Do NOT generate recommendations that lack a traced reason.

Record for each recommendation:

  • Type (merge / extract / pipeline / new / remove)
  • Affected files (paths)
  • Traced reason (which weakness or project characteristic)
  • Priority (high / medium / low)
  • Effort estimate (small / medium / large)

Verification: All recommendations have type, affected files, traced reason, and priority.

Task 5: Produce Analysis Report

Goal: Write structured report to .rcc/{timestamp}-analysis.md.

Important: Read references/report-template.md for the full 6-section report format.

Report sections:

  1. Project Overview — language, framework, project type, team signals
  2. Component Inventory — all components with type, scope, path, line count
  3. Weakness Findings — categorized by severity, with category and suggested fix
  4. Restructuring Recommendations — grouped by type, with traceability
  5. Rules Health Summary — metrics table with threshold alerts
  6. Summary — overall assessment and recommended next steps

Rules Health Summary (include in report):

## Rules Health Summary
| Metric                        | Value | Status |
|-------------------------------|-------|--------|
| CLAUDE.md lines               |       |        |
| Global rules count / lines    |       |        |
| Session-start total lines     |       |        |
| Path-scoped rules             |       |        |
| Rules with procedural content |       |        |
| Dead glob patterns            |       |        |

Thresholds: CLAUDE.md > 200 lines = WARNING. Session-start total > 300 = WARNING. Any dead glob = WARNING.

Verification: Report written with all 6 sections complete.

Task 6: Present Findings to User

Goal: Show the user the full analysis AND restructuring recommendations.

Present ALL findings with detail. Do NOT summarize into brief bullet points:

  1. Project overview: language, framework, project type, notable conventions
  2. Component inventory: each component found, its type, and current state
  3. Critical issues: what's wrong, why it matters, and suggested fix
  4. Warnings: what could be improved and the impact of not fixing
  5. Restructuring recommendations: grouped by priority (high → medium → low)
  6. Overall assessment with rationale

Anti-pattern: "Found 3 critical issues, 2 warnings" without explaining what they are is NOT presenting. The user must see enough detail to understand each finding.

Wait for user confirmation before proceeding.

Handoff: After user confirms, ask user to choose next step:

  • "建議明確,直接進入規劃" → invoke planning-agent-systems skill, pass analysis report path as context
  • "需要進一步探索" → invoke brainstorming-workflows skill, pass analysis report path as context

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I know the issues"
  • "I know the project type"
  • "Only major issues matter"
  • "Skip the report"
  • "Skip project scanning"
  • "Cross-checks take too long"
  • "One pass is enough"
  • "Recommendations are obvious"

Common Rationalizations

ThoughtReality
"I know the issues"Systematic checklist catches what intuition misses.
"I know the project type"package.json alone doesn't tell you it's a monorepo. Scan properly.
"Only major issues matter"INFO issues compound. Document everything.
"Skip the report"Reports enable before/after comparison. Essential for refactoring.
"Skip project scanning"Recommendations without project context are guesses. Scan first.
"Cross-checks take too long"Cross-component issues are the hardest to find later. Check now.
"One pass is enough"Different categories reveal different issues. Check all 11.
"Recommendations are obvious"Obvious to you isn't obvious to the user. Document with traceability.

References

Applying Agent Systems

Overview

Applying agent systems IS orchestrating writing- skill invocations in the correct order.*

Read the component plan, invoke the appropriate writing-* skill for each component, verify each one succeeds before moving to the next.

Core principle: Never create components directly. Always invoke the writing-* skill. Skills encode best practices that direct creation bypasses.

Routing

Pattern: Chain Handoff: user-confirmation Next: reviewing-agent-systems Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Read component plan
  2. Execute component creation (one task per component from plan)
  3. Verify system integration

Announce: "Created N tasks. Starting execution..."

Task 1: Read Component Plan

Goal: Load the component plan and prepare execution order.

Read: .rcc/*-plan.md (most recent)

Create a TaskCreate for each component in the plan's execution order:

  • "[applying] Create CLAUDE.md"
  • "[applying] Create rule: [name]"
  • "[applying] Create hook: [name]"
  • etc.

Verification: All components from plan have corresponding tasks.

Task 2+: Execute Component Creation

Goal: For each component in order, invoke the correct writing-* skill.

Execution order (MUST follow):

  1. CLAUDE.md → invoke writing-claude-md
  2. Rules → invoke writing-rules (one per rule)
  3. Hooks → invoke writing-hooks (one per hook)
  4. Skills → invoke writing-skills (one per skill)
  5. Agents → invoke writing-subagents (one per agent)

For each component:

  1. Invoke the writing-* skill with the plan's specifications
  2. Wait for skill to complete
  3. Verify the component was created correctly
  4. Mark task complete
  5. Move to next component

Important constraints:

  • All writes happen in main conversation. NEVER delegate writing-* skill invocations to subagents. Subagents cannot reliably write to .claude/ directories.
  • One component at a time. Don't batch. Each writing-* skill has its own creation process.
  • Pass plan context. When invoking a writing-* skill, provide the relevant section from the component plan as context.

Verification: Each component exists and passes the writing-* skill's own validation.

Final Task: Verify System Integration

Goal: Verify all components work together.

Checklist:

  • CLAUDE.md exists and is under 200 lines
  • All planned rules exist with correct paths: globs
  • All planned hooks are registered in .claude/settings.json
  • Hooks return correct exit codes (test with sample input)
  • All planned skills have valid frontmatter
  • No conflicts between CLAUDE.md and rules
  • No duplicate logic across components

Handoff: "所有元件已建立並驗證。要進行品質審查嗎?"

  • If yes → invoke reviewing-agent-systems skill

Verification: All checklist items pass.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I can write this component directly, skip the writing-* skill"
  • "Dispatch a subagent to write the rule"
  • "Create multiple components in parallel"
  • "Skip verification, the writing-* skill handles it"
  • "Deviate from the plan, I have a better idea"

All of these mean: You're about to bypass quality gates. Follow the process.

Common Rationalizations

ExcuseReality
"Write directly"Writing-* skills encode structured process + review. Bypass = weak components.
"Use subagent"Subagents can't write to .claude/. Will silently fail.
"Parallel creation"Components depend on each other. CLAUDE.md before rules before hooks.
"Skip verification"Integration issues only appear when components interact. Verify.
"Better idea"The plan was user-approved. Discuss changes, don't silently deviate.

Brainstorming Workflows

Overview

Brainstorming workflows IS targeted exploration of how users actually work, what frustrates them, and what can be automated.

The analysis report tells you what the system looks like; brainstorming tells you what the user needs. These are different data sources — never skip one because the other exists.

Core principle: Ask about failures before wishes.

Routing

Pattern: Chain Handoff: user-confirmation Next: planning-agent-systems Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Import analysis findings
  2. Pipeline mode exploration
  3. Pain point discovery
  4. Routine task identification
  5. Human intervention point discovery
  6. Component type judgment
  7. Produce workflow summary

Announce: "Created 7 tasks. Starting execution..."

Task 1: Import Analysis Findings

Goal: Load analysis report and let user select which findings to address.

If analysis report path was provided:

  1. Read the analysis report
  2. Present restructuring recommendations grouped by priority
  3. Ask: "The analysis report suggests these improvements. Which ones do you want to address this time?"
  4. Present as checklist for user to select
  5. Selected items become requirements in workflow summary

If no analysis report: Note that no analysis was done, proceed to Task 2.

Skip questions in later tasks that the analysis already answered.

Verification: User has confirmed which findings to address (or no analysis exists).

Task 2: Pipeline Mode Exploration

Goal: Determine how workflows connect and what state management they need.

Important: Read references/exploration-questions.md for the question bank (Pipeline section).

Rules:

  • Ask ONE question at a time about workflow entry points, step counts, work scope
  • Classify each workflow as owner-pipe or chain-pipe
  • Determine if script-managed state is needed (based on step count + work scope)
  • Skip questions answered by the analysis report

Verification: Each identified workflow has mode + state management decision.

Task 3: Pain Point Discovery

Goal: Find where the current agent system fails or is missing.

Important: Read references/exploration-questions.md for the question bank (Pain Point section).

Rules:

  • Ask about past failures, missing automation, repeated corrections
  • For each pain point, note the likely component type (rule / hook / skill / CLAUDE.md)
  • Ask ONE question at a time

Verification: Pain points documented with root cause and component type.

Task 4: Routine Task Identification

Goal: Find repetitive small tasks that could be automated.

Important: Read references/exploration-questions.md for the question bank (Routine Task section).

Rules:

  • Ask about daily repetitive work, search patterns, format/check tasks
  • For each task, note automation approach and component type
  • Ask ONE question at a time

Verification: Routine tasks documented with automation approach.

Task 5: Human Intervention Point Discovery

Goal: Find where humans must review, approve, or intervene in the workflows.

Important: Read references/exploration-questions.md for the question bank (Human-in-the-Loop section).

Rules:

  • Ask about irreversible operations, external visibility, trust boundaries
  • For each intervention point, note the type: review checkpoint / confirmation gate / guardrail trigger
  • These findings directly affect Task 6 — intervention points determine which components need user-confirmation handoff vs auto-invoke
  • Ask ONE question at a time

Required question — quality gate loop:

Ask: "When a reviewer reports issues, do you want fixes applied automatically before re-reviewing (auto loop), or do you want to confirm each fix before continuing (manual loop)?"

Record the answer — this determines whether review skills use auto-invoke or user-confirmation handoff to the next fixing step.

Verification: Intervention points documented with type and affected workflow step. Quality gate loop preference recorded.

Task 6: Component Type Judgment

Goal: Map every discovered need to the right component type.

For each pain point, routine task, intervention point, and analysis finding:

  • Behavioral constraint → rule
  • Automated check → hook (PostToolUse or PreToolUse)
  • Multi-step workflow → skill
  • Independent execution → agent (subagent)
  • Simple instruction → CLAUDE.md addition

Present the mapping to user for confirmation.

Challenge any over-engineering: "Can this be a rule instead of a skill?"

Read references/anthropic-patterns.md for the complexity ladder — prefer lowest level that works.

Verification: Every need mapped to component type, user confirmed.

Task 7: Produce Workflow Summary

Goal: Write structured summary to .rcc/{timestamp}-workflows.md.

Important: Read references/summary-template.md for the full summary format.

Include: pipeline mode mapping, pain points, routine tasks, human intervention points, component recommendations.

Handoff: "Workflow summary complete. Continue to plan agent system components?"

  • If yes → invoke planning-agent-systems skill, pass workflow summary path

Verification: Summary written with all sections filled.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I already know from the analysis"
  • "Skip the questions"
  • "Multiple questions saves time"
  • "This obviously needs a skill"
  • "Skip past failures"
  • "The user knows what they want"

Common Rationalizations

ThoughtReality
"I already know from the analysis"Analysis finds system weaknesses. Users reveal workflow needs. Different data.
"Skip the questions"Questions surface needs that code scanning can never find.
"Multiple questions saves time"Multiple questions overwhelm. One at a time.
"This obviously needs a skill"Most workflows need less than you think. Check the complexity ladder.
"Skip past failures"Past failures are the highest-value context. Always ask.
"The user knows what they want"Users describe solutions, not problems. Dig for the actual need.

References

Creating Plugins

Overview

Creating plugins IS scaffolding a distributable agent engineering package.

A plugin is the distribution unit for agent engineering — it bundles skills, commands, agents, hooks, MCP servers, and LSP configs into a single installable package. Plugins are not just "skill containers" — they can provide complete workflows with automated enforcement (hooks), external tool access (MCP), and language intelligence (LSP).

Core principle: Plugins are reusable across projects. Keep them focused and well-documented.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Gather requirements
  2. Create directory structure
  3. Generate plugin manifest
  4. Create initial skill
  5. Write README
  6. Document version bump locations in plugin CLAUDE.md
  7. Test installation

Announce: "Created 7 tasks. Starting execution..."

Task 1: Gather Requirements

Goal: Understand what the plugin should contain.

Questions to ask:

  • What is the plugin name? (kebab-case)
  • What capability does it provide?
  • What skills should it include?
  • Who is the author?

Naming rules:

  • Kebab-case only: my-plugin
  • Avoid: helper, utils, anthropic, claude
  • Max 64 characters

Verification: Can state plugin name and purpose in one sentence.

Task 2: Create Directory Structure

Goal: Scaffold the plugin directory.

Plugin Structure

<plugin-name>/
├── .claude-plugin/
│   └── plugin.json      # Manifest
├── skills/              # Capabilities (auto-discovered)
│   └── <skill-name>/
│       ├── SKILL.md
│       └── references/  # On-demand loaded docs
├── commands/            # Slash command aliases (auto-discovered)
│   └── <command>.md
├── agents/              # Subagent definitions (auto-discovered)
│   └── <agent>.md
├── hooks/               # Lifecycle hooks (auto-discovered)
│   └── hooks.json
├── .mcp.json            # MCP server configs (auto-discovered)
├── .lsp.json            # Language server configs (auto-discovered)
└── README.md

Key Variables for Plugin Skills

In SKILL.md content (substituted at runtime):

VariablePurpose
${CLAUDE_SKILL_DIR}This skill's directory — use to reference bundled scripts/data regardless of CWD
${CLAUDE_SESSION_ID}Current session ID
$ARGUMENTS / $NArguments passed when invoking the skill

In hooks/hooks.json only — NOT available in SKILL.md content:

VariablePurpose
${CLAUDE_PLUGIN_ROOT}Plugin install directory (changes on update — do not write here)
${CLAUDE_PLUGIN_DATA}Persistent data directory that survives updates (~/.claude/plugins/data/{id}/)

Skills can also inject live data using shell commands (execute as preprocessing before Claude sees content). See references/plugin-templates.md for exact shell-injection syntax (inline form, plugin-internal file form, multi-line fenced form, and PowerShell setup).

If the plugin includes scripts or hooks: Read cross-platform-scripts.md for mandatory cross-platform rules (paths, shell commands, line endings).

Verification: Directory structure created with all required paths.

Task 3: Generate Plugin Manifest

Goal: Create the plugin.json manifest file.

Important: Read references/plugin-templates.md for manifest format, required fields, and marketplace structure.

Verification: plugin.json is valid JSON with required fields.

Task 4: Create Initial Skill

Goal: Create the first skill using the writing-skills workflow.

Important: Invoke the writing-skills skill.

Do not write SKILL.md directly. The writing-skills skill ensures:

  • Proper frontmatter format
  • TDD baseline testing
  • Quality review via skill-reviewer

Verification: Initial skill created and passes skill-reviewer.

Task 5: Write README

Goal: Document the plugin for users.

Important: Read references/plugin-templates.md for README template.

Verification: README has installation instructions and skill list.

Task 6: Document Version Bump Locations in Plugin CLAUDE.md

Goal: Plugin root CLAUDE.md lists every file containing this plugin's version string, so Claude can sync them correctly regardless of whether release automation is in place.

Why: Plugin has 3+ version fields (plugin.json, marketplace.json entry, README headers). Release-automation scripts (release-please, semantic-release) fail in various ways — cross-package path limits, marker scope collisions, CI permission issues. CLAUDE.md is authoritative session guidance; when a commit bumps version, Claude reads it and syncs every location. Scripts remain optional — not required by this skill.

Action:

  1. Enumerate every file containing this plugin's version string (typically plugin.json, marketplace entry, README headers in both languages)
  2. Create <plugin-root>/CLAUDE.md with a "Version Bump Locations" section listing:
    • Each file path + field (e.g., plugin.json → version)
    • Cross-package or manual-only locations flagged explicitly
    • Conventional Commits → version mapping (fix: → patch, feat: → minor, feat!: / BREAKING CHANGE: → major)
    • Commit scope convention (e.g., feat(plugin-name): for multi-plugin repos)

Optional release automation: If the user explicitly asks for release-please / semantic-release, see references/plugin-templates.md for config templates. Do not prompt for it here — it is orthogonal to this task.

Verification: <plugin-root>/CLAUDE.md exists and lists every file containing a version string for this plugin.

Task 7: Test Installation

Goal: Verify the plugin installs and works correctly.

Install locally:

claude plugin marketplace add <repo-path-or-url>
claude plugin install <plugin-name>@<marketplace-name>

Verify skills are discoverable and load correctly. Clean up: claude plugin uninstall <plugin-name> (or remove). Note: there is no claude plugin add command; the install flow is two-step (marketplace then plugin).

Verification: Plugin installs without errors, skills are discoverable and load correctly.

Red Flags - STOP

  • "Add skills later"
  • "Skip README"
  • "Skip testing"
  • "One big skill"
  • "Version later"
  • "Skip plugin CLAUDE.md, version sync is obvious"
  • "Release automation will handle it, no need to document"

Common Rationalizations

ThoughtReality
"Add skills later"Empty plugins are useless. Ship with at least one.
"Skip README"Undocumented plugins don't get used.
"Skip testing"Broken installs frustrate users. Test it.
"One big skill"Multiple focused skills > one bloated skill.
"Version later"Version from day 1. Semantic versioning matters.
"Skip plugin CLAUDE.md"3+ version fields drift silently. CLAUDE.md is the fallback when automation breaks.
"Automation will handle it"Release-please etc. fail on cross-package paths, marker scopes, CI perms. Document so Claude can recover.

Publishing

Once your plugin is ready:

  1. Local sharing: Share the directory path
  2. Git hosting: Push to GitHub/GitLab
    /plugin marketplace add username/repo
    /plugin install plugin-name@marketplace-name
    
  3. npm (if applicable): Publish to npm registry

References

Dispatching Parallel Agents

Overview

Dispatching parallel agents IS trading compute for confidence or throughput.

A single Agent call is one bet. N Agent calls in one message is N bets — they execute concurrently and you pick or merge. The runtime fans out automatically when multiple Agent tool uses appear in a single response; serializing by mistake (one Agent call per response) wastes the entire benefit.

Core principle: Parallelism is a property of the dispatch (one message, N tool uses), not of the agents themselves.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Classify the dispatch pattern

  1. Choose agents and inputs
  2. Fan out in a single message
  3. Merge results
  4. Report to user

Announce: "Created 5 tasks (0–4). Starting execution..."

Task 0: Classify the Dispatch Pattern

Goal: Pick exactly one pattern. Mixing patterns = confused merge step.

PatternWhenInputsMerge strategy
P-Thread (parallel, divergent)Independent subtasks, each agent owns a sliceN different promptsConcatenate — each result stands alone
F-Thread (Best-of-N, fusion)One hard question, want confidence or cherry-pickN identical promptsVote / diff / cherry-pick
Scout (throw-away recon)Unfamiliar territory, want to learn before committingOne scout prompt, discard the codeRead scout's findings → write better main prompt
B-Thread (nested orchestrator)One sub-agent dispatches further sub-agentsSingle Agent call to an orchestrator agentOrchestrator handles its own merge

Anti-patterns:

  • "I'll fan out 5 agents to write the same file" — they collide. Fanout is for read-only or sliced-write tasks.
  • "I'll fan out then iterate on each" — that's serial, not parallel. Decide the dispatch shape upfront.
  • "Best-of-N for a deterministic question" — if the answer is git log, one agent suffices. F-Thread costs N× tokens; pay only when judgment varies.

Verification: Can name the pattern in one word and justify it in one sentence.

Task 1: Choose Agents and Inputs

Goal: Pick the agent type per call and the prompts.

Agent selection:

NeedUse
Read-only researchExplore (Haiku, fast, no Write/Edit)
PlanningPlan
Code review (F-Thread voting)Project reviewer agents (e.g. rcc:skill-reviewer)
General multi-stepgeneral-purpose

Prompt design for fanout:

  • Each prompt is self-contained — agents do not see this conversation, do not see each other's output.
  • For F-Thread: identical prompts, identical context. The only variable is the agent's stochastic output.
  • For P-Thread: explicit slice in each prompt — "you handle X, ignore Y."
  • For Scout: tell the scout it's a scout — "your output will be discarded; report what you learned, what files you touched, where you got stuck."

Tool set: Pass minimal tools. Fanout amplifies any tool the agent has — five Edits in parallel = five chances to corrupt the same file.

Verification: Each prompt readable cold, no implicit context, tool set scoped.

Task 2: Fan Out in a Single Message

Goal: Issue all N Agent calls in one assistant turn.

Why this matters: the runtime parallelizes tool uses within a single message. Splitting across turns serializes them and you pay round-trip latency × N.

Correct shape:

[one assistant message]
  Agent(prompt=A, ...)
  Agent(prompt=B, ...)
  Agent(prompt=C, ...)

Wrong shape (serial):

[message 1] Agent(A) → wait → [message 2] Agent(B) → wait → ...

Background flag: for long-running fans (>2 min each), set run_in_background: true so the main turn doesn't block. The runtime notifies on completion.

Verification: All Agent calls visible in a single assistant message.

Task 3: Merge Results

Goal: Collapse N outputs into one decision or report.

Merge strategies by pattern:

PatternStrategy
P-ThreadConcatenate sections. Each agent owned a slice; the slices compose.
F-Thread (vote)Count agreement. ≥ ⌈N/2⌉+1 agree → that answer wins. Disagreement → escalate to user.
F-Thread (diff)Show user the N outputs side-by-side. User picks or cherry-picks.
F-Thread (cherry-pick)Take the strongest part of each — only when outputs are structured (e.g. YAML lists you can union).
ScoutDiscard scout's code. Extract the lessons (files touched, blockers found) into the next prompt.

Reviewer F-Thread special case:

When voting reviewer agents (e.g. 3× rcc:skill-reviewer), if YAML outputs disagree on pass, the safe default is fail — any reviewer flagging an issue counts.

Verification: A single artifact (decision, file, report) emerges from N inputs.

Task 4: Report to User

Goal: Make the parallel dispatch legible.

Report shape:

  • State the pattern: "Ran F-Thread, 3 reviewers."
  • Show the merge: "All 3 passed" or "2 pass / 1 fail — flagging the failing concern."
  • Surface dissent — never silently drop the minority output.

Verification: User can audit which agent said what without re-running.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I'll just run them one at a time, it's the same thing"
  • "Fanout is overkill for this"
  • "Best-of-N for everything makes results better"
  • "I'll fan out 5 agents to edit the same file"
  • "Scout is wasteful, just write the real prompt"
  • "Hide the dissenting reviewer, the others passed"

All of these mean: You're about to lose the value of parallel dispatch. Follow the process.

Common Rationalizations

ExcuseReality
"Serial is simpler"Serial costs N× wall-clock. The whole point is the wall-clock saving.
"More agents = better answer"F-Thread costs N× tokens. Use it for judgment-heavy questions, not lookups.
"Scout is throwaway, skip it"The scout's blockers are intel. Skipping = re-discovering them yourself.
"Fanout writes are fine"Two agents writing the same file race. Fanout writes only on disjoint slices.
"Pick the best output silently"The user can't audit a hidden decision. Surface dissent.

References

  • writing-subagents — design agents that survive fanout
  • User-level investigating skill — scout pattern detail (lives outside this plugin)

Fetching Claude Docs

Overview

Fetching Claude docs IS pulling the latest official Anthropic specification before designing or reviewing any Claude Code component.

This skill exists because the project has historically drifted from official docs (e.g. self-invented <law> block removed in v7.1, invalid context: fork on agents fixed in v9.3, inherit anti-pattern formalized only in v10.9.2). Always pull current spec rather than rely on cached memory.

Core principle: Return official source verbatim with URL. Do NOT paraphrase — paraphrasing reintroduces drift.

Routing

Pattern: Skill Steps Handoff: none Next: caller skill resumes its Task 1 with fetched spec as input

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Identify component type and question
  2. Resolve URL from llms.txt
  3. Fetch official spec via WebFetch
  4. Return verbatim excerpt + URL to caller

Announce: "Created 4 tasks. Starting execution..."

Task 1: Identify Component Type and Question

Goal: Pin down what to fetch.

Inputs expected from caller:

  • component: one of subagent | skill | hook | rule | slash-command | plugin | plugin-marketplace | settings | mcp | output-style | statusline | memory | agent-team | best-practices
  • question: specific aspect (e.g. "frontmatter fields", "tool inheritance", "trigger description format")

If caller did not provide: ask user via AskUserQuestion before fetching.

Verification: component is a recognizable Claude Code concept (subagent, skill, hook, etc.) — no static list to match against; llms.txt is the authoritative source in Task 2.

Task 2: Resolve URL from llms.txt

Goal: Pull the official URL index and locate the page for this component. llms.txt is the only source of truth — no static URL table is kept in this skill.

Action:

WebFetch
  url: https://code.claude.com/docs/llms.txt
  prompt: "Return all entries related to: <component>. Include both
           reference and guide URLs if both exist. Quote the URLs verbatim."

Then pick the URL matching the question type:

  • spec / fields / schema / frontmatter → reference page (e.g. hooks.md)
  • workflow / usage / examples → guide page (e.g. hooks-guide.md)
  • both relevant → fetch reference first, guide second in Task 3

Cache: WebFetch has built-in 15-minute cache. The same llms.txt request in the same session is free, so calling this skill multiple times per session has near-zero overhead. Cross-session cost is one ~5KB fetch — negligible.

Why no static URL map: Hard-coded URLs drift (Anthropic restructures docs). llms.txt is small enough that fetching it every time is cheaper than maintaining a stale map.

Verification: Resolved URL ends with .md and is on code.claude.com.

Task 3: Fetch Official Spec

Goal: Pull live content from Anthropic.

Action:

WebFetch
  url: <resolved URL>
  prompt: "Extract the section addressing: <question>. Return verbatim
           excerpts including all rules, frontmatter fields, examples, and
           warnings. Do NOT paraphrase. Include section headers."

Cache: WebFetch has built-in 15-minute cache — repeated calls in the same session are cheap.

On redirect: Follow the redirect URL with a fresh WebFetch.

On failure (non-2xx): Re-fetch https://code.claude.com/docs/llms.txt (bypassing cache if possible) to confirm whether the URL has moved or been removed. Report the change to caller.

Verification: Response contains a section header matching the question topic.

Task 4: Return to Caller

Goal: Hand back structured spec for the caller skill to consume.

Output format (return to caller):

source: <full URL>
fetched_at: <ISO timestamp>
component: <component>
question: <original question>
spec_excerpt: |
  <verbatim official text — preserve markdown formatting>
key_rules:
  - <rule 1 quoted from official text>
  - <rule 2 ...>
official_examples:
  - <example block as written in docs>
warnings:
  - <any "Important" / "Note" / "Warning" callouts from the docs>

Verification: YAML parses; source is a valid URL; spec_excerpt is non-empty.

When to Trigger This Skill

TriggerAction
User says "create/write/modify a [component]"Fetch component spec BEFORE design
User asks "what's the official way to..."Fetch relevant docs
Reviewer flags a frontmatter field as suspiciousFetch field spec to confirm
Plugin maturity migrationFetch plugins-reference + plugin-marketplaces
Editing settings.json or hooksFetch settings + hooks reference
Designing model selection or tool restrictionsFetch sub-agents.md

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I already know the spec from training data"
  • "We just fetched this last week, it can't have changed"
  • "The cached SKILL.md text is enough"
  • "Paraphrasing the spec is fine, saves tokens"
  • "Skip the fetch, the user is in a hurry"

All of these mean: drift is about to happen. Fetch.

Common Rationalizations

ExcuseReality
"I know the official spec"Anthropic ships docs updates weekly. Your knowledge is stale by definition.
"WebFetch is slow"15-min cache makes repeats free. First fetch < 3s.
"Just summarize from memory"Summary = drift source. v7.1's <law> removal happened because nobody fetched.
"User won't notice"Reviewer will. Or six months later when official spec changed.
"Token cost too high"Drift cost is higher: rework, breaking changes, false confidence.

References

This skill intentionally keeps no static URL table. llms.txt is small (~5KB) and Anthropic restructures docs occasionally; fetching the live index every time is cheaper and safer than maintaining a stale map.

Improving Skills

Overview

Improving skills IS refactoring documentation for clarity and effectiveness.

Analyze current state, research best practices, apply targeted improvements.

Core principle: Improve what exists—don't rewrite from scratch unless necessary.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Analyze current skill
  2. Gather project context
  3. Research best practices
  4. Identify improvements
  5. Apply improvements
  6. Validate and review

Announce: "Created 6 tasks. Starting execution..."

Task 1: Analyze Current Skill

Goal: Understand the skill's current state.

Read the skill:

cat <skill-path>/SKILL.md
ls -la <skill-path>/

Document:

  • Purpose: What does it do?
  • Triggers: What activates it?
  • Structure: How is it organized?
  • References: What supporting files exist?
  • Issues: What problems are apparent?

Common issues:

  • Vague triggers in description
  • Missing verification criteria
  • No task list enforcement
  • Missing Red Flags/Rationalizations
  • Content that should be in references

Verification: Have documented purpose, triggers, and issues.

Task 2: Gather Project Context

Goal: Understand how the skill fits the project.

Search for usage:

grep -r "[skill-name]" . --include="*.md"

Questions:

  • How often is this skill used?
  • What files does it typically work on?
  • Are there project-specific conventions it should follow?
  • Does it overlap with other skills?

Verification: Understand skill's role in project context.

Task 3: Research Best Practices

Goal: Find current best practices for the skill's domain.

WebSearch:

[skill domain] best practices [current year]
[skill domain] patterns

Optional: External skills search

If claude-skills-mcp is available:

mcp__claude-skills-mcp__search_skills query="[skill domain]"

Compare with community implementations.

Verification: Have list of best practices to consider.

Task 4: Identify Improvements

Goal: Create specific improvement plan.

Check against standards:

  • Description states what the skill does, then "Use when..." triggers
  • Description doesn't enumerate workflow steps
  • Task Initialization present if multi-step
  • Has verification for each task
  • Red Flags / Rationalizations present if there's real risk
  • Body < 300 lines
  • Details in references

Improvement types:

IssueImprovement
Vague triggersAdd specific "Use when..." phrases
No task listAdd Task Initialization section
No verificationAdd verification criteria per task
No Red FlagsAdd anti-rationalization section
Too longExtract to references
OutdatedUpdate to current best practices

Verification: Have specific list of improvements to make.

Task 5: Apply Improvements

Goal: Make targeted edits to the skill.

Important: Make focused edits, not full rewrites.

Order of changes:

  1. Fix frontmatter (description)
  2. Add Task Initialization if the flow is multi-step
  3. Add verification criteria
  4. Add Red Flags / Rationalizations if there's real risk
  5. Extract verbose content to references

For each change:

  • Make the edit
  • Verify it's correct
  • Move to next change

Verification: All identified improvements applied.

Task 6: Validate and Review

Goal: Verify skill meets quality standards.

Validation:

python3 "${CLAUDE_SKILL_DIR}/../writing-skills/scripts/validate_skill.py" <skill-path>

Or manual checklist:

  • Frontmatter valid
  • Description states what the skill does, then "Use when..." triggers
  • Has Task Initialization
  • All tasks have verification
  • Has Red Flags
  • Has Rationalizations
  • Body < 300 lines

Quality review:

Invoke skill-reviewer subagent:

Task tool:
- subagent_type: "rcc:skill-reviewer"
- prompt: "Review skill at [path]"

Outcomes:

  • Pass → Done
  • Needs Fix → Fix and re-run
  • Fail → Consider full rewrite with writing-skills

Verification: skill-reviewer returns "Pass".

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Just rewrite the whole thing"
  • "Skip research, I know best practices"
  • "This skill is fine as-is"
  • "Skip validation, changes are small"
  • "Red Flags aren't needed for this skill"

All of these mean: You're about to make things worse. Follow the process.

Common Rationalizations

ExcuseReality
"Full rewrite"Targeted fixes preserve what works. Edit, don't rewrite.
"Skip research"Best practices evolve. Check current standards.
"Fine as-is"If you're here, something needs improvement. Find it.
"Skip validation"Small changes can break things. Validate.
"No Red Flags"Every discipline skill needs anti-rationalization.

References

  • Use writing-skills skill for full rewrites
  • Use skill-reviewer subagent for quality review
  • See writing-skills/references/ for standards

Initializing Projects

Overview

Initializing projects IS bootstrapping with modern best practices, then optionally setting up an agent system.

Don't just create files—research current docs, confirm with the user, then build.

Core principle: Research current best practices. Don't assume—verify with official docs.

Routing

Pattern: Chain Handoff: user-confirmation Next: migrating-agent-systems(agent system 唯一入口) Chain: bootstrap

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Gather requirements
  2. Research best practices
  3. Write blueprint and get confirmation
  4. Bootstrap project
  5. Validate project
  6. Offer agent system setup

Announce: "Created 6 tasks. Starting execution..."

Task 1: Gather Requirements

Goal: Understand what project to create.

First, ask Project Type:

Project TypeFollow-up Questions
Frontend SPALanguage, Framework, UI Library, Styling, State, Testing
Full-stack AppAbove + ORM, Database, API Style, Auth
API ServiceLanguage, Framework, ORM, Validation, Auth
CLI ToolLanguage, Package Manager, Testing
LibraryLanguage, Build Tool, Testing, Docs

Ask iteratively. Skip already-answered or N/A questions.

Verification: Have answers to all relevant questions for project type.

Task 2: Research Best Practices

Goal: Find current best practices for the chosen stack.

Use WebSearch to find:

  • Latest stable version of framework
  • Official CLI/init command with current flags
  • Recommended project structure
  • Current best practices

Important: Don't assume versions or flags from training data. Official docs change frequently.

Verification: Have official init command and current version numbers from live sources.

Task 3: Write Blueprint and Get Confirmation

Goal: Present a complete plan for user approval before creating anything.

Present the blueprint directly to the user (do NOT write to a file — the project directory doesn't exist yet).

Blueprint Format

## Stack
- Language: [name] [version]
- Framework: [name] [version]
- Package manager: [choice]

## Initialization Command
[official CLI command with flags]

## Project Structure
[Expected directory layout after init]

## Key Dependencies
[Core packages to add, with purpose]

Important: Present FULL detail. The user must see exact versions, flags, and dependency list to catch mistakes.

Ask: "這個 blueprint 正確嗎?要開始執行嗎?"

If rejected: Revise based on feedback, present again.

Verification: User has reviewed the full blueprint and explicitly approved.

Task 4: Bootstrap Project

Goal: Run the official CLI to create the project.

Process:

  1. Run the official init command from blueprint
  2. Install additional dependencies if needed
  3. Apply any post-init configurations

Verification: Project directory exists with expected structure.

Task 5: Validate Project

Goal: Verify the project builds and runs.

Checklist:

  • Project builds without errors
  • Project runs without errors (dev server starts, CLI executes, tests pass)
  • Directory structure matches blueprint

If validation fails: Fix issues before proceeding. Do NOT skip to agent system setup with a broken project.

Verification: All checklist items pass.

Task 6: Offer Agent System Setup

Goal: Ask the user if they want a Claude Code agent system for this project.

Present options:

  • Set up agent system — invoke migrating-agent-systems(唯一入口,由該 skill 決定範圍與流程)
  • Skip — no agent system

If set up:

  • Invoke migrating-agent-systems skill
  • It will detect maturity = None and route to the full pipeline (brainstorm → plan → apply → review)
  • Agent system 的範圍(full vs minimal)由 migrating-agent-systems 內部與使用者討論決定

If Skip:

  • End

Important: 不得繞過 migrating-agent-systems 直接呼叫 writing-claude-md 或其他 component skill。migrating-agent-systems 是 agent system 設定的唯一入口。

Verification: User's choice is executed or skipped.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I know the current version"
  • "Skip research, I've done this before"
  • "Don't need user confirmation"
  • "A brief summary is enough for confirmation"
  • "Write the blueprint to a file first"
  • "Skip validation, it's a fresh project"

All of these mean: You're about to create a weak foundation. Follow the process.

Common Rationalizations

ExcuseReality
"I know the version"Versions change monthly. Verify with official docs.
"Skip research"Best practices evolve. Check live sources.
"Skip confirmation"Blueprint approval prevents wasted effort.
"Brief summary"Brief summaries hide wrong decisions. Show full detail.
"Write blueprint to file"Project directory doesn't exist yet. Present inline.
"Fresh = working"Fresh projects can have config issues. Validate.

Skill Chain Reference (Bootstrap)

StepSkillPurpose
agent systemmigrating-agent-systems唯一入口。Detects None maturity → brainstorm → plan → apply → review

Migrating Agent Systems

Overview

Migrating agent systems IS routing to the correct workflow based on project state.

Detect whether an agent system already exists, then invoke the appropriate skill chain. This skill is a thin router — all logic lives in the specialized skills.

Core principle: Detect, don't assume. Route, don't implement.

Routing

Pattern: Tree Handoff: auto-invoke Next: analyzing-agent-systems | brainstorming-workflows Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Detect and assess existing agent system
  2. Read or create .rcc/config.yml
  3. Rules refactoring proposal
  4. Route to appropriate skill chain

Announce: "Created 4 tasks. Starting execution..."

Task 1: Detect and Assess Existing Agent System

Goal: Determine the project's agent system maturity level, not just presence/absence.

Check for Claude Code components:

  • CLAUDE.md (project root)
  • .claude/ directory
  • .claude/rules/ directory
  • .claude/settings.json
  • .claude/skills/ directory

Check for other AI tool configurations:

  • .cursorrules (Cursor)
  • .github/copilot-instructions.md (GitHub Copilot)
  • .windsurfrules (Windsurf)
  • .aider.conf.yml (Aider)

Check for existing conventions:

  • .editorconfig
  • Linter configs (.eslintrc*, .prettierrc*, ruff.toml, etc.)
  • CI/CD pipeline configs (.github/workflows/, .gitlab-ci.yml)

Maturity classification:

LevelCriteriaRoute
NoneNo components found→ brainstorming-workflows
SeedOnly other AI tool configs exist (.cursorrules, etc.) — no Claude Code components→ brainstorming-workflows (import existing configs as starting context)
PartialHas CLAUDE.md or rules but missing skills/hooks→ analyzing-agent-systems
EstablishedHas CLAUDE.md + rules + at least one skill or hook→ analyzing-agent-systems

For Seed level: Record which other AI configs exist and their content summary — these become input for the brainstorming step to avoid re-discovering known conventions.

Verification: Clear maturity classification with evidence (which components found, which missing).

Task 2: Read or Create .rcc/config.yml

Goal: Ensure the project has a .rcc/config.yml recording migration state and key decisions. Idempotent — on re-runs, this prevents redoing work. Also migrate legacy folders if present.

Read references/config-schema.md for the full schema and field semantics.

Process:

2a — Legacy folder migration (run BEFORE creating config)

RCC v11 moved artifact output from docs/agent-system/ + docs/validation-reports/ into .rcc/. If legacy folders exist, migrate them first.

Detect legacy folders:

test -d docs/agent-system && echo "legacy-agent-system"
test -d docs/validation-reports && echo "legacy-validation"

If either exists:

  1. List contents to the user:

    偵測到舊版路徑。RCC v11 起產出改寫到 .rcc/。建議遷移:

    • docs/agent-system/ → .rcc/ (找到 N 份檔案)
    • docs/validation-reports/ → .rcc/validation/ (找到 M 份檔案)

    要執行遷移嗎?(預設:是)

  2. If confirmed:

    • mkdir -p .rcc/validation
    • For each file in docs/agent-system/:
      • Tracked (git ls-files <file> returns path) → git mv <file> .rcc/<basename>
      • Untracked → mv <file> .rcc/<basename>
    • For each file in docs/validation-reports/:
      • Same tracked/untracked split → target .rcc/validation/<basename>
    • If docs/agent-system/archive/ exists, move wholesale: git mv docs/agent-system/archive .rcc/archive (or mv for untracked)
    • rmdir docs/agent-system docs/validation-reports after emptying
    • If docs/ is now empty, rmdir docs/ too
  3. If declined: record in decisions_log that legacy folders were kept, and note this skill will not re-offer migration unless forced.

  4. Report to user: summary of files moved with tracked/untracked counts.

2b — Handle .rcc/config.yml

  1. Check .rcc/config.yml exists.

  2. If exists: Load it. Report to user:

    偵測到 .rcc/config.yml:上次遷移 {migration.last_at},使用 rcc {migration.last_rcc_version}。本次 rcc 版本為 {current}。

    • release automation: {release_automation.decision} / {release_automation.tool}
    • safety settings: {settings_scope.safety_bypass}
    • If last_rcc_version < current: offer re-migration to pull newer patterns
    • If config_version: 1 with a models: block: delete the block and bump to config_version: 2 (component parameters are not recorded in config; see references/config-schema.md)
    • If migration.completed: true and versions match: ask if user wants to re-run anyway or proceed to specific task
  3. If missing: Create .rcc/ directory (if not already by 2a) and write a new config.yml. Ask the user (one round of questions):

    要記錄以下決策到 .rcc/config.yml 嗎?
    1. Release automation(版號自動化):release-please / semantic-release / 跳過
    2. 安全規則 (safety_bypass) 要放在:
       - `.claude/settings.json`(團隊共享,checked in)[預設]
       - `.claude/settings.local.json`(個人,gitignored)
       - `~/.claude/settings.json`(使用者全域)
    

    (不詢問、不記錄模型或 effort——這些由元件 frontmatter 控制,預設 inherit session model。)

  4. Write config.yml with user answers + detected state from Task 1. Populate decisions_log with each confirmed answer. If 2a migrated folders, add a log entry recording that.

  5. Also ensure .gitignore does not exclude .rcc/ (config.yml must be tracked).

Verification: Legacy folders migrated or decline recorded. .rcc/config.yml exists, all key fields populated, user has confirmed or declined each decision.

Task 3: Rules Refactoring Proposal

Goal: Analyze CLAUDE.md and rules content, propose splitting into appropriate locations.

Skip condition: If maturity is None or Seed, skip this task (no existing content to refactor).

Process:

  1. Read all CLAUDE.md files and .claude/rules/*.md
  2. For each content block, classify:
CategoryCriteriaAction
Abstract directive (what/why)Broad, applies to all workKeep in CLAUDE.md
Path-related directiveTargets specific file types or directoriesExtract to path-scoped rule
Procedural content (how/steps)Multi-step process, code blocks as instructionsExtract to skill
Outdated/duplicateConflicts with or duplicates other contentDelete
  1. Produce refactoring proposal table:
## Rules Refactoring Proposal

| # | Source | Summary | Category | Action | Target |
|---|--------|---------|----------|--------|--------|
  1. Present proposal to user for confirmation
  2. If confirmed, invoke writing-rules or writing-skills for each item

Verification: User has confirmed or skipped the proposal.

Task 4: Route to Appropriate Skill Chain

Goal: Invoke the correct starting skill based on maturity level.

Language recommendation (all routes): Before routing, advise the user: "All skills, rules, CLAUDE.md, and prompt files should be written in English for best model performance. Use your native language only in CLAUDE.md communication rules (e.g., 'respond in Traditional Chinese'). Shall I proceed in English for all agent system files?"

If None:

  • Announce: "New project with no existing configuration. Starting workflow exploration..."
  • Invoke brainstorming-workflows skill
  • Chain: brainstorming → planning → applying → reviewing → refactoring

If Seed (other AI configs found):

  • Announce: "Found existing [tool] configuration. Importing as starting context for workflow exploration..."
  • Read and summarize existing configs (.cursorrules, copilot instructions, etc.)
  • Invoke brainstorming-workflows skill, passing the config summary as pre-loaded context
  • Chain: brainstorming → planning → applying → reviewing → refactoring

If Partial or Established:

  • Announce: "Existing agent system detected ([list components found]). Starting analysis..."
  • If existing files contain non-English prompts, flag as a migration item: "Found non-English prompt files — recommend converting to English for optimal model performance."
  • Invoke analyzing-agent-systems skill
  • Chain: analyzing → brainstorming → planning → applying → reviewing → refactoring

Verification: Correct skill invoked based on maturity level, with appropriate context passed.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I can see it's a new project, skip detection"
  • "Just start building without analyzing"
  • "Handle everything in this skill instead of routing"
  • "Skip brainstorming, I know what's needed"
  • "Ignore the .cursorrules file, it's for a different tool"
  • "It has a CLAUDE.md so it's established" (could be empty or minimal)

All of these mean: You're about to bypass the specialized skills. Route correctly.

Common Rationalizations

ExcuseReality
"Skip detection"Hidden configs exist. Always check.
"Build without analyzing"Existing systems have history. Analyze first.
"Handle here"This skill is a router. Logic lives in specialized skills.
"Skip brainstorming"Assumptions about workflows lead to misfit systems.
"Ignore other AI configs".cursorrules and copilot instructions contain validated conventions worth importing.
"Has CLAUDE.md = established"Quality matters more than presence. A 3-line CLAUDE.md is seed-level at best.

Skill Chain Reference

StepSkillPurpose
0analyzing-agent-systemsScan + 11-category weakness detection (if partial/established)
1brainstorming-workflowsRole-based workflow exploration + simplicity assessment
2planning-agent-systemsArchitecture flowchart + dependency-driven component planning
3applying-agent-systemsInvoke writing-* skills per phase
4refactoring-agent-systemsReview + cleanup

References

Migrating Plugins

Overview

Migrating plugins IS identifying what to work with, then routing to the correct workflow.

A workspace may contain existing plugins, a script project that should become a plugin, or nothing. This skill discovers the state, asks the user what they want, resolves paths, then routes.

Core principle: Discover what exists. Ask the user. Then route.

Routing

Pattern: Tree Handoff: auto-invoke Next: creating-plugins | validating-plugins → refactoring-plugins Chain: plugin

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Discover and select target
  2. Assess state and classify
  3. Propose conversion (if pre-plugin)
  4. Route to appropriate skill chain

Announce: "Created 4 tasks. Starting execution..."

Plugin vs Project: Key Differences

ComponentProjectPlugin
CLAUDE.md✓✗
.claude/rules/✓✗
.claude/settings.json✓✗ (plugin has settings.json at root)
.claude-plugin/plugin.json✗✓ (manifest)
marketplace.json✗✓ (if marketplace)
skills/.claude/skills/plugin-root/skills/
agents/.claude/agents/plugin-root/agents/
hooks/.claude/settings.jsonplugin-root/hooks/hooks.json
.mcp.json✓✓
.lsp.json✗✓
bin/✗✓

Task 1: Discover and Select Target

Goal: Find existing plugins or identify a script project to convert.

Discovery strategy (try in order):

  1. Check for marketplace.json — scan for **/.claude-plugin/marketplace.json. Read plugins array for names and source paths.

  2. Check for standalone plugins — scan for **/.claude-plugin/plugin.json. Each parent of .claude-plugin/ is a plugin root.

  3. Check for script project — if no plugins found, scan for signs of a convertible project:

    • Script files (*.sh, *.py, *.js, *.ts) in root or scripts/, src/, bin/
    • README.md describing a tool or utility
    • Package manifest (package.json, pyproject.toml, Cargo.toml)
    • Existing .claude/ directory with skills, commands, or agents
  4. Check user-specified path — if the user provided a path, use it directly.

For each plugin found, record:

  • Name (from plugin.json name field)
  • Root path
  • Version
  • Source path (from marketplace.json if applicable)

If multiple plugins found:

  • Present numbered list, ask which to work on

If exactly one plugin found:

  • Confirm: "Found plugin '[name]' at [path]. Proceed?"

If no plugins but script project detected:

  • Announce: "No plugin found, but this looks like a script project that could become a plugin."
  • List what was found (scripts, README, package manifest, .claude/ configs)
  • Ask: "Do you want to package this as a Claude Code plugin?"

If nothing found:

  • Ask: "Do you want to create a new plugin from scratch?"

Set the target path for all subsequent tasks.

Verification: Target is selected, path is resolved, user has confirmed.

Task 2: Assess State and Classify

Goal: Determine the maturity level of the target.

Maturity classification:

LevelCriteriaRoute
NoneNo plugin, no scripts, user wants new→ creating-plugins
Pre-pluginScript project without .claude-plugin/ — has scripts, tools, or .claude/ configs that can become plugin components→ Task 3 (conversion proposal) → creating-plugins
MinimalHas .claude-plugin/plugin.json but missing skills/agents/hooks→ validating-plugins → refactoring-plugins
CompleteHas manifest + skills + agents or hooks→ validating-plugins → refactoring-plugins

For Pre-plugin, scan and categorize existing assets:

Asset TypeExampleBecomes
Scripts with reusable logicscripts/deploy.sh, tools/lint.pybin/ executables or skill-bundled scripts
Markdown instructions.claude/commands/*.mdskills/ or commands/
Agent definitions.claude/agents/*.mdagents/
Hook scripts.claude/hooks/*hooks/
Skill directories.claude/skills/*/SKILL.mdskills/
MCP server configs.mcp.json.mcp.json
Validation/linting scriptsscripts/validate.pyhooks/

For each asset found, record:

  • Source path
  • Type (script / instruction / agent / hook / skill / config)
  • Suggested plugin component
  • Line count

Run claude plugin validate if .claude-plugin/ exists.

Detect version bump documentation (record for routing):

  • Plugin root CLAUDE.md exists AND contains a version-bump section listing every version-bearing file (plugin.json, marketplace entries, README headers)
  • Record as version_bump_doc: present | absent | partial (partial = CLAUDE.md exists but section missing or incomplete)

Verification: Clear maturity classification with asset inventory. Version bump doc state recorded.

Task 3: Propose Conversion (Pre-plugin Only)

Skip if: Maturity is None, Minimal, or Complete.

Goal: Present a conversion proposal for the script project.

Conversion proposal format:

## Plugin Conversion Proposal

Plugin name: [suggested-name]
Source: [project path]

| # | Source | Type | Plugin Component | Action |
|---|--------|------|-----------------|--------|
| 1 | scripts/deploy.sh | script | bin/deploy.sh | Copy to bin/, make executable |
| 2 | .claude/commands/review.md | instruction | skills/reviewing/SKILL.md | Convert to skill with frontmatter |
| 3 | .claude/agents/checker.md | agent | agents/checker.md | Copy, verify frontmatter |
| 4 | scripts/lint.py | validator | hooks/lint.py + hooks.json | Wrap as PostToolUse hook |
| 5 | README.md | docs | README.md | Adapt for plugin installation |

Version bump doc: [present | absent | partial]
- If absent/partial: `creating-plugins` Task 6 will add the required section to plugin CLAUDE.md during conversion

Present to user for confirmation.

If confirmed:

  • Pass the conversion proposal as context to creating-plugins
  • creating-plugins will use the proposal to pre-populate the plugin structure instead of starting from scratch

If rejected:

  • Ask what to change, revise proposal, present again

Verification: User has confirmed or revised the conversion proposal.

Task 4: Route to Appropriate Skill Chain

Goal: Invoke the correct skill with the target path.

Important: Always pass the target path to downstream skills.

If None:

  • Invoke creating-plugins (its Task 6 ensures plugin CLAUDE.md documents version bump locations)

If Pre-plugin (after Task 3 confirmation):

  • Invoke creating-plugins with the conversion proposal as context (including recorded version_bump_doc state)
  • The proposal tells creating-plugins which files to move/convert instead of scaffolding from scratch
  • creating-plugins Task 6 will fill the plugin CLAUDE.md section based on the recorded state

If Minimal or Complete:

  • Invoke validating-plugins with plugin root path
  • After validation, invoke refactoring-plugins with report, plugin root path, and recorded version_bump_doc state
  • refactoring-plugins Task 7 verifies / fills the plugin CLAUDE.md version-bump section

Verification: Correct skill invoked with target path, context, and version bump doc state.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "I know which plugin they mean"
  • "There's only one plugin, skip asking"
  • "This project can't be a plugin"
  • "Just create a new plugin, ignore existing scripts"
  • "The plugin.json exists so it's complete"
  • "Skip validation, just refactor"
  • "I'll just use the current directory"

All of these mean: You're about to guess instead of discover. Scan, ask, then route.

Common Rationalizations

ExcuseReality
"I know which one"Multiple plugins can exist. Always list and confirm.
"Can't be a plugin"Any project with reusable scripts or instructions can become a plugin.
"Ignore existing scripts"Existing scripts are validated, working code. Reuse them.
"Has manifest = complete"A 3-field plugin.json is minimal at best. Check all components.
"Skip validation"claude plugin validate catches structural issues you can't see by reading.
"Use current directory"Plugin root may be nested. Resolve from marketplace.json or plugin.json.

Skill Chain Reference

StepSkillPurpose
0validating-pluginsBatch scan all files for frontmatter, links, orphans
1refactoring-pluginsHealth-check and fix against official best practices
alt-acreating-pluginsScaffold new plugin (from scratch or from conversion proposal)

Planning Agent Systems

Overview

Planning agent systems IS mapping workflows to components with explicit rationale.

Read the analysis report and workflow summary, decide what to create/modify/delete, identify which writing-* skills to invoke, and get user confirmation before execution.

Core principle: Every component must trace back to a workflow need or a weakness fix. No speculative components.

Routing

Pattern: Chain Handoff: user-confirmation Next: applying-agent-systems Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Read inputs
  2. Design architecture flowchart
  3. Plan components (includes reuse check)
  4. Produce component plan
  5. Get user confirmation

Announce: "Created 5 tasks. Starting execution..."

Task 1: Read Inputs

Goal: Load analysis report (if available) and workflow summary.

Read:

  • .rcc/*-analysis.md (most recent, if exists)
  • .rcc/*-workflows.md (most recent, if exists)
  • .rcc/*-reflection.md (most recent, if exists)

Extract:

  • Weaknesses marked for fixing
  • Workflows to support
  • Conventions to enforce
  • Component recommendations from workflow summary or reflection report
  • Learnings and suggested components from reflection report (if available)

Verification: Have a clear list of requirements from both sources.

Task 2: Design Architecture Flowchart

Goal: Visualize the entire agent system topology before deciding individual components.

Why this comes first: Component lists hide dependency gaps and workflow disconnects. A flowchart forces you to see the whole picture — entry points, decision branches, data flow, and handoff points — before committing to any component.

Important: Read references/anthropic-patterns.md for the six Anthropic workflow patterns, DOT flowchart conventions, and dependency graph template.

Step 1 — Classify workflows into Anthropic patterns using the reference table.

Step 2 — Draw the architecture flowchart in DOT format using the reference conventions.

Step 3 — Build the dependency graph from the flowchart, assigning phases by dependency depth.

Step 4 — Check prior learnings before architecture decisions:

Read past reflection reports (.rcc/*-reflection.md) and .rcc/config.yml decisions_log for known failure modes and prior decisions.

  • Match each prior learning against the current design
  • Adjust architecture to avoid repeating known failure modes
  • Document how each relevant learning is addressed

Step 5 — Identify the simplest viable subset:

Ask: "What is the minimum set of components that delivers value?"

  • Mark each component as core (must-have for any workflow to work) or enhancement (improves but not required)
  • Phase 1 should contain ONLY core components
  • Present the phased rollout to user for early feedback

Verification: Architecture flowchart produced showing all workflows, patterns identified, dependency graph built, phases assigned, prior learnings addressed.

Task 3: Plan Components

Goal: Decide action for each component type.

Important: Read references/component-planning.md for the evaluation table, decision criteria, size constraints, and writing skill assignments.

Use the dependency graph from Task 2 to determine execution order. Do NOT use a fixed order — let dependencies drive sequencing. Components in the same phase with no mutual dependencies can be built in parallel.

Agent layer ordering — follow this sequence when planning agents:

  1. Sonnet implementer first — establish the core implementation agent before anything else. This is the foundation all other layers depend on.

    Implementer capability analysis (MANDATORY before moving on): Based on what the implementer will do (from the planned workflows), identify what project-specific knowledge it needs that Claude Code does NOT already know:

    QuestionIf yes, plan this component
    Are there non-standard conventions specific to this project/framework?CLAUDE.md update or scoped rule
    Do file types need different conventions (e.g., API vs. domain model)?Path-scoped rule per file type
    Should any quality constraint be enforced deterministically (not advisory)?Hook with exit code 2
    Are there project-specific gotchas Claude would get wrong without being told?CLAUDE.md or rule

    Exclude: Standard language conventions, general best practices, anything a linter already enforces, anything Claude knows from training. Only plan components that add project-specific signal.

  2. Orchestrator second — add only if dispatch complexity justifies a dedicated coordinator. If there is only one implementer doing a single job, a separate orchestrator adds overhead without value.

    • Use Haiku when dispatch is simple: explicit task list, direct assignment, no ambiguity.
    • Use Sonnet when decomposition requires reasoning: ambiguous requirements, multi-level decisions, dynamic routing.
  3. Opus quality gate / advisor third — add only if (a) a revision loop exists and (b) the output will be mechanically executable by downstream Sonnet. Without both conditions, skip Opus.

Safety baseline (MANDATORY check): Every plan must include or explicitly waive the safety bypass prevention rules. These are baseline defaults, not project-specific additions:

RuleScopeSource
git-safety.mdGlobalwriting-rules/references/examples.md
deploy-safety.mdGlobal (if project deploys)same
destructive-ops.mdGlobalsame

Pair with reflecting skill's safety_bypass event detection for prevent-detect-learn loop. If the user already has equivalent global rules in ~/.claude/rules/, note them in the plan as "inherited — no project-level duplicate needed". If the user waives safety rules, record the justification explicitly.

Verification: Each planned component has a traced rationale and assigned writing-* skill. Agent layers follow the ordering above. Implementer capability analysis completed. Safety baseline resolved (planned, inherited, or explicitly waived). No conflicts identified.

Task 4: Produce Component Plan

Goal: Write structured plan to .rcc/{timestamp}-plan.md.

Important: Read references/plan-template.md for the full plan format including architecture flowchart, pattern mapping, dependency graph, and component sections.

Verification: Plan written with complete execution order and traceability.

Task 5: Get User Confirmation

Goal: Present plan and get explicit approval.

Present the FULL plan to user. Show: architecture flowchart, pattern mapping, dependency graph with phases, each component's purpose and content, weakness fixes, core/enhancement classification, and estimated scope per phase.

Anti-pattern: Listing component names without explaining what they do is NOT presenting.

Ask: "Does this plan look good? Ready to start building components?"

Handoff: After user confirms → invoke applying-agent-systems skill, pass plan path

Verification: User has reviewed the full plan and explicitly approved.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Skip the flowchart"
  • "Create everything"
  • "Skip traceability"
  • "Skip confirmation"
  • "Skip reuse check"
  • "One big rule"
  • "Fixed order is fine"

Common Rationalizations

ThoughtReality
"Skip the flowchart"Component lists hide dependency gaps. The flowchart reveals what's missing.
"Create everything"YAGNI. Only create what traces to a need.
"Skip traceability"Untraceable components become mystery debt.
"Skip confirmation"User approval prevents wasted effort.
"Skip reuse check"Duplicating existing skills creates conflicts.
"One big rule"Multiple focused rules > one bloated rule.
"Fixed order is fine"Dependencies vary per project. Let the graph decide.

References

Refactoring Agent Systems

Overview

Refactoring agent systems IS applying clean code principles to agent configurations.

Re-analyze after changes, compare before/after, fix remaining issues, simplify over-engineering.

Core principle: Refactoring without measurement is guessing. Analyze, then change, then verify.

Routing

Pattern: Skill Steps Handoff: none Next: none Chain: main (terminal)

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Load review findings
  2. Prioritize issues
  3. Execute refactoring
  4. Final verification
  5. Produce refactoring report
  6. Archive pipeline documents

Announce: "Created 6 tasks. Starting execution..."

Task 1: Load Review Findings

Goal: Load the review report as the basis for refactoring.

If review report path was provided (from reviewing-agent-systems):

  1. Read the review report
  2. Extract all Critical and Major issues
  3. These are your refactoring targets

If no review report (standalone invocation):

  1. Invoke reviewing-agent-systems skill first to produce a report
  2. Then continue with the report's findings

Verification: Have a list of specific issues to fix from the review report.

Task 2: Prioritize Issues

Goal: Classify and order issues from the review report for fixing.

Priority order:

  1. Critical — must fix before shipping
  2. Major — should fix for quality
  3. Minor — nice to have, fix if time permits

Present the prioritized list to user. Do NOT summarize — show each issue with its component, severity, and planned fix.

Ask: "這些修正項目正確嗎?要開始修正嗎?"

Verification: User has confirmed the prioritized fix list.

Task 3: Execute Refactoring

Goal: Fix remaining and new issues.

Refactoring actions (in priority order):

Issue TypeActionMethod
Duplicate logic across componentsMerge or extract to ruleMain conversation edits
Conflicting instructionsUnify or remove oneMain conversation edits
Over-engineered componentSimplify (YAGNI)Main conversation edits
Weak skill triggerImprove descriptionMain conversation edits
Heavy read-only work in main contextMove it to a subagent, or add context: fork to the skillMain conversation edits
CLAUDE.md too longMove content to rules/skillsMain conversation edits
Skill missing assetAdd scripts/, templates/, or references/Create directly — no user confirmation needed

Important: All edits happen in main conversation. Never delegate refactoring writes to subagents.

For each refactoring action:

  1. Identify the specific change
  2. Make the edit
  3. Verify the fix resolves the issue
  4. Move to next action

Verification: All REMAINING and NEW issues addressed.

Task 4: Final Verification

Goal: Confirm no critical issues remain.

Re-run the relevant reviewer agents on components that were modified in Task 3.

Pass criteria:

  • Zero CRITICAL issues from any reviewer
  • All Major issues from the original review are resolved
  • No new issues introduced by refactoring

If critical issues remain: Return to Task 3 and fix.

Verification: All modified components pass their reviewer.

Task 5: Produce Refactoring Report

Goal: Document what was changed and why.

Write to: .rcc/{timestamp}-refactoring-report.md

Report format:

# Agent System Refactoring Report

**Date:** YYYY-MM-DD HH:MM

## Changes Made

| # | Component | Change | Rationale |
|---|-----------|--------|-----------|

## Before/After Comparison

| Metric | Before | After |
|--------|--------|-------|
| Components | N | N |
| Critical issues | N | 0 |
| Warnings | N | N |
| Total lines (CLAUDE.md) | N | N |

## Remaining Items (INFO)

- [Low priority items for future consideration]

Verification: Report accurately reflects all changes.

Task 6: Archive Pipeline Documents

Goal: Move all pipeline documents from the current run to the archive.

Steps:

  1. Create archive directory: .rcc/archive/{YYYY-MM-DD}/
  2. Move ALL *.md files from .rcc/ to the archive directory (excluding the archive/ directory itself)
  3. Commit the archive move
mkdir -p .rcc/archive/{YYYY-MM-DD}
mv .rcc/*.md .rcc/archive/{YYYY-MM-DD}/
git add .rcc/
git commit -m "chore: archive pipeline documents from {YYYY-MM-DD}"

Replace {YYYY-MM-DD} with today's actual date.

If no documents exist in .rcc/: Skip this task (nothing to archive).

Verification: .rcc/ contains only the archive/ directory. All pipeline documents are in the dated archive subdirectory.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Skip re-analysis, I just built this"
  • "No need to compare, everything is new"
  • "Use a subagent to make the edits"
  • "Skip final verification, I just fixed it"
  • "The report is busywork"
  • "Skip archiving, the docs aren't hurting anything"

All of these mean: You're about to leave mess behind. Follow the process.

Common Rationalizations

ExcuseReality
"Skip re-analysis"Building introduces new issues. Always re-analyze.
"Skip comparison"Without before/after, you can't prove improvement.
"Subagent edits"Subagents can't write to .claude/. Use main conversation.
"Skip verification"Refactoring can break things. Verify.
"Skip report"Report documents decisions for future maintainers.
"Skip archiving"Accumulated documents confuse future pipeline runs. Archive.

Refactoring Plugins

Overview

Refactoring plugins IS aligning plugin structure with official Claude Code best practices.

Run health checks, detect structural drift, fix anti-patterns, and verify the result. Plugins differ from agent systems — they have an official schema (plugin.json), auto-discovery conventions, and distribution requirements.

Core principle: A plugin that fails health check will fail in production. Measure first, then fix.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Identify plugin target
  2. Run health check
  3. Analyze findings against checklist
  4. Present refactoring plan
  5. Execute refactoring
  6. Verify fixes
  7. Verify version bump documentation in plugin CLAUDE.md

Announce: "Created 7 tasks. Starting execution..."

Task 1: Identify Plugin Target

Goal: Locate the plugin to refactor.

Discovery order:

  1. User provided a path → use it
  2. Current directory has .claude-plugin/plugin.json → use it
  3. Search for */.claude-plugin/plugin.json in working directory
  4. Ask user to specify

Record:

  • Plugin root path
  • Plugin name (from plugin.json or directory name)
  • Whether a marketplace.json exists upstream

Verification: Have a valid plugin directory with .claude-plugin/plugin.json.

Task 2: Run Health Check

Goal: Execute the automated health check script.

Step 1: Run claude plugin validate <plugin-path> (official CLI).

Step 2: Run extended health check (bash-first, three-runner fallback with brace grouping):

{ command -v uv >/dev/null 2>&1 && uv run "${CLAUDE_SKILL_DIR}/scripts/validate_plugin.py" <plugin-path>; } \
  || { python3 --version >/dev/null 2>&1 && python3 "${CLAUDE_SKILL_DIR}/scripts/validate_plugin.py" <plugin-path>; } \
  || python "${CLAUDE_SKILL_DIR}/scripts/validate_plugin.py" <plugin-path>

The script integrates CLI validation and adds checks for manifest, structure, skills quality, commands, agents, path safety, and version sync.

Capture output for analysis in Task 3.

Verification: Health check completed with error/warning counts.

Task 3: Analyze Findings Against Checklist

Goal: Deep analysis beyond the automated script.

Important: Read references/plugin-health-checklist.md for the full checklist.

The script catches structural issues. Manual analysis catches:

  • Skill trigger overlaps
  • Cross-component duplication
  • Distribution readiness problems
  • README documentation gaps
  • Hook safety concerns

For each finding, record:

  • Category (from checklist)
  • Severity: CRITICAL / WARNING / INFO
  • Component affected
  • Specific issue
  • Suggested fix

Verification: All 9 checklist categories evaluated.

Task 4: Present Refactoring Plan

Goal: Show user the full findings and planned fixes.

Present ALL findings with detail. Do NOT summarize:

  1. Health check script output (errors and warnings)
  2. Manual analysis findings by severity
  3. Planned fix for each issue

Format:

#SeverityCategoryComponentIssuePlanned Fix

Ask: "以上是插件健康檢查結果,要開始修正嗎?"

Verification: User has confirmed the refactoring plan.

Task 5: Execute Refactoring

Goal: Fix all confirmed issues.

Important: Read references/plugin-structure-rules.md for official rules and execution order.

Important: All edits in main conversation. Never delegate writes to subagents.

Verification: Each fix applied and individually verified.

Task 6: Verify Fixes

Goal: Re-run health check to confirm all issues resolved.

Process:

  1. Re-run the Step 2 fallback chain (uv run → python3 → python) on the refactored plugin
  2. Verify zero CRITICAL errors
  3. Verify all WARNING items from Task 3 are resolved
  4. Check no new issues introduced

If issues remain: Return to Task 5 and fix.

Produce final report with changes made (component, change, rationale) and before/after health check metrics.

Verification: Health check passes with zero errors.

Task 7: Verify Version Bump Documentation in Plugin CLAUDE.md

Goal: Plugin root CLAUDE.md lists every file containing this plugin's version string.

Detection: Read <plugin-root>/CLAUDE.md. Check for a section (typically "Version Bump Locations") that enumerates:

  • Each file path + field holding this plugin's version (plugin.json, marketplace entry, README headers)
  • Cross-package or manual-only locations flagged explicitly
  • Conventional Commits → version mapping

If absent or incomplete: Add/update using the format defined in creating-plugins Task 6.

Release automation is orthogonal: Whether or not release-please / semantic-release is configured, the plugin CLAUDE.md is still required. Scripts fail; CLAUDE.md is the fallback Claude reads every session.

Verification: <plugin-root>/CLAUDE.md documents every version-bearing file for this plugin.

Red Flags - STOP

  • "Skip health check"
  • "Structure looks fine"
  • "Fix without showing"
  • "Skip re-verification"
  • "Simple plugin"
  • "I know the official structure"

Common Rationalizations

ThoughtReality
"Skip health check"Scripts catch what eyes miss. Always run it.
"Structure looks fine"Anti-patterns hide in config files. Check all 9 categories.
"Fix without showing"User must confirm before structural changes.
"Skip re-verification"Fixes can break other things. Re-run the script.
"Simple plugin"Simple plugins still need valid manifests and naming.
"I know the official structure"Official structure evolves. Verify against the checklist.

References

  • references/plugin-health-checklist.md — Full 9-category plugin health checklist
  • Health check script: ${CLAUDE_SKILL_DIR}/scripts/validate_plugin.py (cross-platform, supports uv run)

Refactoring Skills

Overview

Refactoring skills IS applying clean code principles to documentation.

Consolidate, simplify, extract shared conventions, remove redundancy.

Core principle: Fewer focused skills > many overlapping skills.

Routing

Pattern: Tree Handoff: mixed (auto-invoke per classification) Next: analyzing-agent-systems | writing-skills | writing-rules Chain: maintenance

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Discover all skills
  2. Analyze and classify
  3. Execute refactoring plan
  4. Extract shared conventions
  5. Validate results
  6. Generate report

Announce: "Created 6 tasks. Starting execution..."

Task 1: Discover All Skills

Goal: Find all skills in the project.

Search locations:

find . -name "SKILL.md" -type f 2>/dev/null
ls -la .claude/skills/ 2>/dev/null

Also check:

  • Plugin directories
  • User-level skills (~/.claude/skills/)

Document:

  • Skill name
  • Location
  • Brief description

Verification: Complete list of all skills with locations.

Task 2: Analyze and Classify

Goal: Classify each skill for action, informed by systematic weakness analysis.

First: Invoke analyzing-agent-systems skill to get a comprehensive analysis report covering all 8 weakness categories. This replaces manual analysis.

Then classify each skill using both the analysis report and manual assessment:

Classification Matrix

StatusCriteriaAction
KeepWell-structured, unique purpose, no weaknesses flaggedNone
RefactorAnalysis flagged weaknesses but valuableUse writing-skills to improve
MergeAnalysis found overlap with another skillConsolidate into primary
ExtractAnalysis found duplicated conventionsMove to rule file
DeleteRedundant, unused, or supersededRemove entirely

Analysis-Informed Questions

For each skill, check against analysis report:

  1. Did analysis flag routing/trigger weaknesses for this skill?
  2. Did analysis find context management issues?
  3. Did analysis detect overlap with other skills?
  4. Is this skill referenced in any broken chain?
  5. Does it follow current standards? (frontmatter, line count, sections)

Optional: External Search

If claude-skills-mcp is available:

mcp__claude-skills-mcp__search_skills query="[skill domain]"

Compare with community implementations. Better patterns exist?

Verification: Each skill has a classification and action, informed by analysis report.

Task 3: Execute Refactoring Plan

Goal: Apply the classified actions.

For Skills to Refactor

Invoke the writing-skills skill with the existing skill path.

For Skills to Merge

  1. Identify the primary skill (keep this one)
  2. Extract unique content from secondary skill
  3. Integrate into primary skill
  4. Delete secondary skill directory

For Skills to Delete

  1. Confirm no dependencies (grep for skill name)
  2. Remove entire skill directory
  3. Remove from any manifest references

Important: One action at a time. Verify after each.

Verification: All classified actions executed.

Task 4: Extract Shared Conventions

Goal: Move duplicated conventions to rule files.

Signs of shared conventions:

  • Same constraint appears in 2+ skills
  • Convention is about "what" not "how"
  • Convention is path-specific

Process:

  1. Identify duplicated constraint
  2. Invoke writing-rules skill to create rule
  3. Remove constraint from all skills
  4. Verify rule auto-injects correctly

Verification: No duplicated conventions across skills.

Task 5: Validate Results

Goal: Verify all remaining skills are valid.

For each skill:

python3 "${CLAUDE_SKILL_DIR}/../writing-skills/scripts/validate_skill.py" <skill-path>

Or manual checklist:

  • Frontmatter has name and description
  • Description states what the skill does, then "Use when..." triggers
  • Body < 300 lines
  • No duplicated conventions (now in rules)

Verification: All remaining skills pass validation.

Task 6: Generate Report

Goal: Document what was done.

Report Format

## Refactoring Summary

### Skills Analyzed: N

### Actions Taken:
| Skill | Action | Notes |
|-------|--------|-------|
| skill-name | kept/refactored/merged/deleted | details |

### Rules Extracted:
| Rule | Source Skills |
|------|--------------|
| rule-name | skill-a, skill-b |

### Recommendations:
- [Future improvements]

Verification: Report accurately reflects all changes.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Keep all skills, they might be useful"
  • "Too much overlap is fine"
  • "Don't need to extract conventions"
  • "Skip validation, I just fixed them"
  • "Report is busywork"

All of these mean: You're about to leave mess behind. Follow the process.

Common Rationalizations

ExcuseReality
"Keep everything"Unused skills are clutter. Delete them.
"Overlap is fine"Overlap = confusion. Merge or differentiate.
"Skip extraction"Duplicated conventions drift. Extract to rules.
"Skip validation"Fixed skills can still be broken. Validate.
"Skip report"Report documents decisions for future you.

Skill Chain Reference (Maintenance)

StepSkillPurpose
1analyzing-agent-systemsWeakness analysis (invoked in Task 2)
2writing-skillsRefactor individual skills (invoked in Task 3)
3writing-rulesExtract shared conventions (invoked in Task 4)
4skill-reviewerQuality validation (subagent, Task 5)

References

  • Use writing-skills skill for improving skills
  • Use writing-rules skill for extracting conventions
  • Use skill-reviewer subagent for quality checks

Reflecting

Overview

Reflecting IS surfacing candidate learnings, then deepening only the ones the user picks.

Scan the session, list what is worth reflecting on with a one-line reason each, and let the user choose. Do not force every event into a full learning report. Capture before context fades; deepen on demand.

When to reflect: after a significant feature, a resolved bug, repeated failed attempts, an unexpected discovery, or a long session. Don't wait for "later" — context fades fast.

Routing

Pattern: suggest → pick → deepen Hand off: planning-agent-systems, opt-in (only when a learning should become a component)

Stage 1: Suggest Candidates (lightweight)

Scan the conversation for moments worth reflecting on. For each, write ONE line:

[type] short description — why it's worth a look

Types: correction (user corrected you), error (mistake / multiple attempts), discovery (new insight about project/domain/tooling), repetition (same action repeated — automation candidate), safety_bypass (destructive/irreversible action without confirmation, or a safety check skipped).

Rules:

  • No minimum count. A quiet session may yield one candidate, or none. One honest candidate beats a forced three.
  • Do NOT trace routers, locate files, or fill multi-field forms here. Stage 1 is a menu, not a report.
  • safety_bypass is always surfaced, flagged ⚠️ — never bury a skipped safety check, even in a light scan. Watch for: --force / reset --hard / clean -f / branch -D, --no-verify, rm -rf / dropping tables, deleting or editing tests to pass, discarding unfamiliar files, rsync --delete without exclusions, or user interjections ("stop", "don't", "wait", "undo", "rollback").
  • If a pain point was given via $ARGUMENTS, list it first — even if the trace doesn't show it failing.

Present the list and ask: which do you want to deepen? (some, all, or none.)

Stage 2: Deepen Picked Candidates only

For each candidate the user picks:

  1. Extract the learning — what would prevent the failure or repeat the success, and where it applies.
  2. Locate the router — which skill/rule/law/CLAUDE.md routed the behavior. Glob the path; "none" if it came from general knowledge.
  3. Suggest where the fix lands — simplest component that works:
    • one-line convention → rule; immutable project constraint → law; repeated multi-step process → skill; automated check → hook; reference material → doc
    • safety_bypass → rule or law only — never a skill alone (safety needs always-on enforcement). Name the exact command/flag to block.
  4. Debug session — capture two things separately: the bug itself (root cause + prevention rule) and any reasoning error made while debugging.

Write the picked learnings to .rcc/{YYYY-MM-DD}-reflection.md using references/report-template.md.

Stage 3: Land (optional)

Default: present the suggested fixes; let the user apply them.

To turn a learning into a component automatically, hand off to planning-agent-systems with the reflection path. Otherwise stop — do not auto-create components.

Red Flags — STOP

  • "Surface everything as a full learning" → Stage 1 is a menu; only deepen the picks.
  • "Skip the safety_bypass — user didn't complain" → silence ≠ consent. Always surface it, flagged.
  • "Auto-create the component, I know where it goes" → landing is opt-in. Suggest, don't impose.
  • "Nothing worth noting" → scan once more; capture now, context fades.

References

  • references/report-template.md — lightweight reflection list format
  • planning-agent-systems — opt-in, only when turning a learning into a component
  • .rcc/config.yml decisions_log — append new decisions here

Reviewing Agent Systems

Overview

Reviewing agent systems IS running every reviewer against every component.

After components are built, each one must pass its corresponding reviewer agent before moving to refactoring. This is the quality gate between "built" and "ready to ship".

Core principle: Building without reviewing is shipping without testing. Every component type has a reviewer — use it.

Routing

Pattern: Chain Handoff: user-confirmation Next: refactoring-agent-systems Chain: main

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Collect component inventory
  2. Run reviewers
  3. Present review report to user
  4. Get user confirmation

Announce: "Created 4 tasks. Starting execution..."

Task 1: Collect Component Inventory

Goal: Identify all components to review.

Scan for:

Component TypeLocationReviewer Agent
CLAUDE.mdCLAUDE.md or .claude/CLAUDE.mdclaudemd-reviewer
Skills.claude/skills/*/SKILL.mdskill-reviewer
Rules.claude/rules/*.mdrule-reviewer
Hooks.claude/hooks/* + .claude/settings.jsonhook-reviewer
Subagents.claude/agents/*.mdsubagent-reviewer

If a component plan path was provided: Use the plan to identify which components were just created/modified — review only those.

If no plan: Scan all locations and review everything found.

Verification: Complete inventory with component paths and assigned reviewer.

Task 2: Run Reviewers

Goal: Invoke the correct reviewer agent for each component.

For each component, invoke its reviewer:

Agent tool:
- subagent_type: "rcc:[reviewer-name]"
- prompt: "Review [component type] at [path]"

Execution order:

  1. CLAUDE.md → claudemd-reviewer
  2. Rules → rule-reviewer (one per rule)
  3. Hooks → hook-reviewer (one per hook)
  4. Skills → skill-reviewer (one per skill)
  5. Subagents → subagent-reviewer (one per agent)

Collect each reviewer's output:

  • Rating: Pass / Needs Fix / Fail
  • Critical issues
  • Major issues
  • Minor issues

Important: Run all reviewers. Do not skip components because "they were just created by a writing-* skill". Writing-* skills have their own internal review, but system-level review catches cross-component issues.

Verification: Every component has a reviewer result.

Task 3: Present Review Report to User

Goal: Show the user the full review results.

Present ALL findings with detail. Do NOT summarize into brief bullet points.

Report format:

## Agent System Review Report

### Summary

| Component | Type | Reviewer | Rating | Critical | Major | Minor |
|-----------|------|----------|--------|----------|-------|-------|
| [name] | [type] | [reviewer] | Pass/Fix/Fail | N | N | N |

### Detailed Findings

#### [Component Name] — [Rating]

**Critical Issues:**
- [Issue]: [what's wrong, why it matters, suggested fix]

**Major Issues:**
- [Issue]: [what's wrong, why it matters, suggested fix]

**Minor Issues:**
- [Suggestion]

Anti-pattern: "5 components reviewed, 2 need fixes" without listing what the fixes are is NOT presenting. Show every finding.

Write report to: .rcc/{timestamp}-review-report.md

Verification: Report written with all findings from all reviewers.

Task 4: Get User Confirmation

Goal: User decides whether to proceed to refactoring.

Ask: "Review 完成。要繼續進行重構修正嗎?"

Handoff: After user confirms → invoke refactoring-agent-systems skill, pass review report path

Verification: User has explicitly confirmed.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Writing-* skills already reviewed, skip system review"
  • "Only review components that look wrong"
  • "Skip reviewer for simple components"
  • "A brief summary is enough for the user"
  • "Don't need all 5 reviewers"

All of these mean: You're about to ship unreviewed components. Follow the process.

Common Rationalizations

ExcuseReality
"Already reviewed by writing-*"Writing-* reviews individual quality. System review catches cross-component issues.
"Only review suspicious ones"You can't judge quality by looking. Run the reviewer.
"Simple = correct"Simple components can still have wrong globs, missing fields, or duplicated logic.
"Brief summary is enough"Users need full details to decide which issues to fix vs accept.
"Not all types present"Review what exists. Skip types with zero components.

Validating Plugins

Overview

Runs batch structural validation across all plugin components, writes a report, then proposes fixes.

Core principle: Validation should be cheap to run and easy to act on. The report is the source of truth — read it fully before proposing any fixes.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks:

  1. Run validator script
  2. Read report
  3. Propose fixes

Announce: "Created 3 tasks. Starting execution..."

Task 1: Run Validator Script

Goal: Execute validate_all.py and capture the report path.

{ command -v uv >/dev/null 2>&1 && uv run "${CLAUDE_SKILL_DIR}/../../hooks/validate_all.py" --user-root; } \
  || { python3 --version >/dev/null 2>&1 && python3 "${CLAUDE_SKILL_DIR}/../../hooks/validate_all.py" --user-root; } \
  || python "${CLAUDE_SKILL_DIR}/../../hooks/validate_all.py" --user-root

--user-root additionally scans ~/.claude/skills, ~/.claude/agents, and ~/.claude/rules. The PostToolUse hook only fires on files edited in-session inside a project, so components under ~/.claude/ — loaded in every session — are never validated by it. Report entries for those files carry absolute paths; everything else is cwd-relative.

Parse stdout for:

  • report:<path> — path to the generated Markdown report
  • issues:<N> files, <M> warnings — summary if issues exist
  • status:clean — no issues

If script fails to run: Check that validate_all.py exists at plugins/rcc/hooks/validate_all.py. If missing, stop and report.

Verification: Script ran, report path captured.

Task 2: Read Report

Goal: Read the full validation report and understand all issues.

Read the file at the report path captured in Task 1.

For each issue entry, note:

  • File path
  • Warning type: extra frontmatter field / broken link / orphaned file / invalid variable / plugin validate
  • Specific value flagged

If no issues (status:clean): Report to user that everything is valid and mark all tasks complete.

Verification: All issues catalogued.

Task 3: Propose Fixes

Goal: For each issue, propose a concrete fix. Group by file.

Fix patterns:

Warning typeFix
extra frontmatter field: "X"Remove field X from frontmatter (or rename if it's a valid field with wrong name)
broken link: path/to/file.mdEither create the missing file, or remove the dead link from SKILL.md
orphaned file: path/to/file.mdEither add a markdown link to SKILL.md, or delete the file if unused
invalid variable: ${CLAUDE_PLUGIN_ROOT}Replace with ${CLAUDE_SKILL_DIR}/../../ pattern, or move the reference to hooks/hooks.json
plugin validate: <error>Fix the specific manifest error reported

Present fixes grouped by file. For each file, show the exact edit needed (old → new).

Ask user to confirm before applying any fixes.

Verification: User has reviewed and approved (or rejected) proposed fixes.

Red Flags - STOP

  • "Skip reading the full report" — every issue needs to be seen
  • "Fix issues without user approval" — always confirm before editing
  • "Guess what the fix should be" — derive from the warning type table above
  • "Run the script without capturing report path" — the path is needed for Task 2

Common Rationalizations

ExcuseReality
"The validator already ran clean"Validator checks structure, not content quality. Manual review catches semantic issues.
"It's just frontmatter"Wrong frontmatter means skills don't trigger, agents get wrong tools, hooks don't fire.
"I'll fix it later"Invalid plugin files silently degrade. Fix now or users hit confusing errors.
"Only one file has issues"One broken link or orphaned file signals systemic neglect. Check everything.

Writing CLAUDE.md

Overview

Writing CLAUDE.md IS establishing project memory that persists across sessions.

CLAUDE.md is context, not enforced configuration. Claude treats it as high-priority guidance loaded every session. For deterministic enforcement, use hooks.

Core principle: Only include what Claude can't figure out from reading the code. Specific and verifiable > vague and aspirational.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Fetch latest official memory/CLAUDE.md spec

  1. Analyze current state
  2. RED - test without proper CLAUDE.md
  3. GREEN - write CLAUDE.md
  4. Add project content
  5. Validate structure
  6. REFACTOR - quality review
  7. Test with new session

Announce: "Created 8 tasks (0–7). Starting execution..."

Task 0: Fetch Latest Official Spec

Goal: Pull the current Anthropic CLAUDE.md / memory spec before designing — never trust cached memory.

Action:

Skill tool: fetching-claude-docs
  component: memory
  question: "CLAUDE.md location precedence (project/user/local), import syntax,
             auto-loading behavior, token cost, recommended structure"

Verification: Received YAML with source: https://code.claude.com/docs/en/memory.md and non-empty spec_excerpt. Use as authoritative reference; if any rule in this SKILL conflicts with the fetched spec, the fetched spec wins.

Task 1: Analyze Current State

Goal: Understand what exists and what's needed.

If CLAUDE.md exists:

  1. Read current content
  2. Check length (target: < 200 lines)
  3. Identify vague or unverifiable instructions
  4. Check if content belongs elsewhere (rules, skills, hooks)

If no CLAUDE.md: Document what Claude would need to know that it can't learn from reading the code.

Verification: Can list specific instructions needed and why each can't be derived from code.

Task 2: RED - Test Without Proper CLAUDE.md

Goal: Observe what Claude gets wrong without guidance.

Process:

  1. Start session with weak/no CLAUDE.md
  2. Ask Claude to perform common project tasks
  3. Note where it uses wrong commands, wrong conventions, wrong paths
  4. Document specific gaps (not vague "drift")

What to look for:

  • Wrong build/test commands
  • Incorrect assumptions about project structure
  • Missing project-specific conventions
  • Wrong language or communication style

Verification: Documented at least 2 specific things Claude got wrong.

Task 3: GREEN - Write CLAUDE.md

Goal: Create specific, verifiable instructions addressing the gaps you documented.

Before writing, walk through prompt-design-principles.md:

  • 5-skeleton framework — CLAUDE.md typically needs Role (what Claude does in this project), Scope (what's in/out), and Standards (concrete rules). Workflow and Completion usually live in skills / rules, not CLAUDE.md.
  • Failure-mode reverse engineering — every MUST / NEVER line should trace to an observed or predicted failure (documented in Task 2 RED), not an aspirational wish.
  • Conditional dispatch — avoid absolute rules that don't hold across all task variants.

What to Include vs Exclude

Filter every line through this question first: "Can Claude derive this from reading the code, package.json, or running ls?" If yes, exclude — it's noise that pushes real signal out of attention budget.

The 2026 ETH Zürich study found that LLM-auto-generated CLAUDE.md files reduced task success by ~3% and increased cost ~20% precisely because they re-stated derivable content. The same study found that named tools/commands in CLAUDE.md are used ~160× more — confirming Claude reads it carefully, so every wasted line displaces a useful one.

Three-axis frame (WHAT / WHY / HOW):

  • WHAT — non-obvious project identity Claude can't infer: monorepo layout, unusual subdirectory roles
  • WHY — rationale for surprising choices: historical constraints, legal/compliance drivers, prior incidents
  • HOW — non-default tooling and commands: bun not npm, uv not pip, custom build scripts, project-specific test filters
Include (Claude can't guess)Exclude (Claude already knows or can derive)
Non-default tooling (bun not npm, uv not pip)Standard language conventions
Build/test/deploy commands with project-specific flagsThings a linter or formatter enforces
Repo conventions (branch naming, PR format)General programming practices
Why a surprising architecture exists (incident, constraint)Big architecture overviews / directory listings (Claude can ls)
Environment quirks, gotchas, prior incidentsDetailed API docs (link instead)
Hidden invariants not visible in codeRestating what package.json / pyproject.toml already says
Anti-patterns previously caught in reviewAspirational "write clean code" / "follow best practices"

CLAUDE.md Structure

Sections: Code Style, Workflow, Architecture, Gotchas. See references/examples.md for complete example.

Writing Rules

Instructions MUST be SPECIFIC, VERIFIABLE, NON-OBVIOUS, and ACTIONABLE.

Use MUST/NEVER/IMPORTANT sparingly — if everything is critical, nothing is.

When to Use Other Mechanisms Instead

If the instruction is...Use...
A focused convention scoped to a directory or file glob.claude/rules/<name>.md with paths: — loads only when Claude reads a matching file, so it costs nothing until relevant
A reusable multi-step workflowA skill in .claude/skills/ (loaded on-demand)
Must NEVER be bypassed (force-push protection, secret-commit block, destructive ops)A hook with exit 2 — text in CLAUDE.md is ~70% compliance, not 100%. Hard rules live in hooks.
Only relevant for certain tasksA skill (loaded on-demand, saves tokens)
Specific to a subdirectory of a monorepoA nested CLAUDE.md inside that subdirectory — Claude Code merges parent + child when working in that path

Conditional Dispatch (for instructions only relevant to specific tasks)

When a section only applies to certain task types (testing, deploying, migrating), wrap it in a conditional block instead of always-on prose. Claude reads the condition and skips the body when it doesn't apply, freeing attention budget for the rest of the file.

<important if="writing or modifying tests">
- Use `createTestApp()` helper for integration tests
- Mock the database with `dbMock` (NEVER hit real DB in unit tests)
</important>

<important if="deploying to production">
- Run `bun build` locally first; CI does not auto-build
- Tag the release before pushing to main
</important>

Use this for: test setup, deploy steps, migration procedures, environment-specific gotchas. Do not wrap core identity (tech stack, build command, project layout) — those need to stay always-on.

Nested CLAUDE.md (monorepos and multi-package repos)

Claude Code merges nested CLAUDE.md files: when working in apps/api/handlers/foo.ts, it loads root CLAUDE.md + apps/CLAUDE.md + apps/api/CLAUDE.md if they exist. Files above the working directory load in full at launch; files in subdirectories below it load on demand, when Claude first reads a file there. Nested files are also not re-injected after /compact — they reload the next time Claude touches that subdirectory. Use this for monorepos:

  • Root CLAUDE.md: project identity, top-level layout, shared commands
  • packages/<name>/CLAUDE.md: package-specific tooling, test command, gotchas
  • apps/<name>/CLAUDE.md: app-specific build, deploy, runtime quirks

Reference: OpenAI's Codex repo uses 88 nested CLAUDE.md files. For a 5+ package monorepo, a single 500-line root file is worse than five 80-line nested files.

Hard Rules — Must Live in Hooks

CLAUDE.md text is advisory: empirical compliance is roughly 70%. For any rule where the 30% miss is unacceptable (force-pushing main, committing secrets, deleting prod data, bypassing pre-commit), encode it as a hook with exit 2 so Claude is mechanically blocked, not asked nicely.

CLAUDE.md may describe the rule for human readers, but the enforcement must be a hook. If you find yourself writing MUST NEVER about a destructive action without a backing hook, you're shipping a 30%-broken safety net.

Verification:

  • < 200 lines (hard target; 60 lines optimal)
  • Every instruction is specific and verifiable
  • No content that belongs in rules, skills, or hooks
  • No vague/obvious guidance ("write clean code")
  • No content that restates README, package.json, or visible directory layout
  • No big architecture overviews / directory listings (Claude can ls)
  • Uses emphasis words (MUST, NEVER) sparingly but effectively
  • Every MUST NEVER about a destructive/irreversible action has a backing hook
  • Task-specific instructions wrapped in <important if="..."> conditional blocks where appropriate
  • Monorepo: subdirectory-specific guidance moved to nested CLAUDE.md files, not crammed into root

Task 4: Add Project Content

Goal: Add project-specific information that helps agent work effectively. Use the section structure from references/examples.md as a starting point.

Token efficiency:

  • CLAUDE.md loads every session — every line costs tokens
  • Move domain knowledge to skills (loaded on-demand)
  • Move file-scoped conventions into .claude/rules/<name>.md with paths: — these load only when Claude touches a matching file, so they leave the always-resident budget entirely
  • A rule without paths: still loads at launch; it buys readability, not tokens
  • Link to detailed docs instead of inlining them (@path imports load at launch too, so they don't save context either)

Verification: Total < 200 lines. Every line earns its place.

Task 5: Validate Structure

Goal: Verify CLAUDE.md is effective and efficient.

Checklist:

  • < 200 lines total
  • Every instruction is specific and verifiable
  • No content duplicated in .claude/rules/ (rules are auto-loaded into context — do NOT Read or Grep rule files; compare against auto-loaded rule content already in context)
  • No multi-step workflows (belongs in skills)
  • No linter-enforceable rules (use hooks instead)
  • Referenced paths actually exist
  • Commands actually work

Verification: All checklist items pass.

Task 6: REFACTOR - Quality Review

Goal: Have CLAUDE.md reviewed by claudemd-reviewer subagent.

Agent tool:
- subagent_type: "rcc:claudemd-reviewer"
- prompt: "Review CLAUDE.md at [path]"

Interpret YAML output:

  • pass: true → Proceed to Task 7
  • pass: false → Fix all issues listed, re-run reviewer, repeat until pass: true

Verification: claudemd-reviewer returns YAML with pass: true.

Task 7: Test with New Session

Goal: Verify CLAUDE.md works in practice.

Process:

  1. Start new Claude Code session in project
  2. Ask Claude to perform common tasks
  3. Verify it uses correct commands, follows conventions
  4. Check it doesn't do things the CLAUDE.md says not to
  5. If Claude asks questions answered in CLAUDE.md → phrasing is ambiguous, fix it

Signs of a good CLAUDE.md:

  • Claude uses the right build/test commands without asking
  • Claude follows project conventions automatically
  • Claude doesn't need correction on documented gotchas

Signs of a bad CLAUDE.md:

  • Claude ignores instructions → file too long, instruction lost in noise
  • Claude asks questions answered in CLAUDE.md → phrasing is ambiguous
  • Claude follows CLAUDE.md but breaks things → instructions are wrong/outdated

Verification: Claude follows documented conventions correctly over 5+ turns.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Skip baseline test, I know what's needed"
  • "Instructions can be general guidance"
  • "Put all project details in CLAUDE.md"
  • "200 lines is too restrictive"
  • "Skip reviewer, it's obviously good"
  • "Add instructions for things a linter can check"
  • "Include standard language conventions"
  • "Restate the README so Claude has the context handy" (it doesn't help — see ETH 2026 study, ~3% drop in success rate)
  • "A big architecture overview helps Claude find files faster" (false — measured zero improvement on time-to-first-relevant-file)
  • "Writing 'NEVER force-push' here will stop it" (no — that's ~70% compliance; needs a hook)
  • "Cram every monorepo package's quirks into root CLAUDE.md" (use nested CLAUDE.md per package)
  • "Always-on prose for test setup is fine" (use <important if="writing tests"> instead)

All of these mean: You're about to create a bloated, ineffective CLAUDE.md.

Common Rationalizations

ExcuseReality
"I know what instructions are needed"You know what YOU think. Baseline reveals actual gaps.
"Instructions can be vague for flexibility"Vague instructions = Claude interprets freely = no control.
"Everything goes in CLAUDE.md"CLAUDE.md = always loaded = expensive. Use skills and rules.
"More instructions = better coverage"More instructions = more noise = important ones get lost.
"Standard practices need documenting"Claude already knows standard practices. Document the exceptions.
"Linter rules belong here"Linter rules belong in linters + hooks. Deterministic > advisory.

References

  • references/examples.md — Complete CLAUDE.md example and good/bad instructions
  • ../../references/prompt-design-principles.md — 5-skeleton framework, failure-mode reverse engineering, conditional dispatch, completion semantics
  • Scaffold script: ${CLAUDE_SKILL_DIR}/scripts/init_claude_md.py — generates initial CLAUDE.md from project structure

Writing Hooks

Overview

Writing hooks IS creating automated quality gates.

Hooks run on Claude Code events (PreToolUse, PostToolUse, etc.) and can block actions with exit code 2.

Core principle: Hooks enforce what humans forget. Fast checks only—slow hooks kill productivity.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Fetch latest official hook spec

  1. Analyze requirements
  2. RED - Test without hook
  3. GREEN - Write hook script
  4. Configure settings.json
  5. Validate behavior
  6. Test blocking
  7. REFACTOR - Quality review

Announce: "Created 8 tasks (0–7). Starting execution..."

TDD Mapping for Hooks

TDD PhaseHook CreationWhat You Do
REDTest without hookWrite code, observe quality issues slip through
Verify REDDocument violationsNote specific issues that should be caught
GREENWrite hookCreate script that catches those issues
Verify GREENTest blockingVerify exit code 2 blocks violating code
REFACTOROptimize speedReduce hook runtime, filter file types

Task 0: Fetch Latest Official Spec

Goal: Pull the current Anthropic hook spec before designing — never trust cached memory.

Action:

Skill tool: fetching-claude-docs
  component: hook
  question: "hook events (PreToolUse, PostToolUse, etc.), matcher syntax,
             exit code contract, settings.json schema, additionalContext field,
             security considerations"

Verification: Received YAML with source: https://code.claude.com/docs/en/hooks.md and non-empty spec_excerpt. Use as authoritative reference; if any rule in this SKILL conflicts with the fetched spec, the fetched spec wins.

Task 1: Analyze Requirements

Goal: Understand what quality gate to create.

Questions to answer:

  • What violation should be blocked?
  • Which files should be checked?
  • What tool/command performs the check?
  • What event triggers the hook?
  • What is the project's primary language? (check package.json, go.mod, Cargo.toml, pyproject.toml, *.csproj, etc.)

Event Selection:

EventWhenUse For
PreToolUseBefore tool runsBlock bad writes before they happen
PostToolUseAfter tool runsValidate written code
UserPromptSubmitBefore prompt processedAdd context to prompts
StopWhen agent tries to end its turnSelf-verify loop — block stop until checks pass (Ralph Wiggum pattern, enables L-Thread)

Verification: Can describe the violation and the command to detect it.

Task 2: RED - Test Without Hook

Goal: Write code WITHOUT the hook. Observe violations that slip through.

Process:

  1. Ask agent to write code in the target file type
  2. Intentionally introduce the violation (bad format, type error, etc.)
  3. Observe that Claude Code doesn't catch it
  4. Document the specific violation

Verification: Documented at least 1 violation that should have been caught.

Task 3: GREEN - Write Hook Script

Goal: Create Python script that catches the violations you documented.

Hook Structure

.claude/hooks/
├── eslint_check.py
├── prettier_check.py
└── typecheck.py

Exit Code Contract

CodeMeaningEffect
0PassContinue, stdout shown in verbose
2BlockAction blocked, stderr fed to Claude
OtherWarningContinue, stderr shown in verbose

Hook Template

See references/static-checks.md for complete hook templates. For performance-optimized security hooks, see references/performance-optimization.md. Key pattern: read JSON from stdin, filter by extension, run check, exit 2 to block.

Stop Event Self-Verify (Ralph Wiggum / L-Thread)

When the agent tries to end its turn, block until deterministic checks pass — turning a one-shot agent into a loop that won't quit until the work is actually done. Use for long-running tasks, refactors, migrations, anything where "I think I'm done" is unreliable.

See references/stop-event-self-verify.md for the hook script and settings.json registration. Critical rule: always check stop_hook_active to bail after one retry — otherwise the agent loops forever on unfixable failures.

Critical Requirements

  • Fast - Under 5 seconds, hooks run synchronously
  • Performance constraints - Total execution < 30s, parallel processing support
  • Graceful degradation - Handle timeouts without blocking development
  • Filter files - Only check relevant extensions
  • Limit output - First 5-10 errors, not all
  • Use Python - Cross-platform, wrapped shell commands. In settings.json command, prefer uv → fallback python3 → fallback python (see cross-platform-scripts.md)
  • Progressive checks - Fast/standard/thorough modes based on context
  • Cross-platform - Must work on macOS, Linux, AND Windows

Windows Compatibility (MANDATORY)

Important: Read cross-platform-scripts.md for full cross-platform rules covering paths, shell commands, line endings, and common pitfalls.

Verification:

  • Script is executable (chmod +x) — skip on Windows
  • Returns exit code 0 for valid files
  • Returns exit code 2 for violations
  • Runs under 5 seconds
  • Uses pathlib.Path for all path operations
  • No shell=True with string commands (use list args)
  • No hardcoded /tmp/ or path separators
  • settings.json command uses three-runner fallback template (uv → python3 --version → python); python3 probed by --version to avoid Windows Microsoft Store stub

Task 4: Configure settings.json

Goal: Register hook in .claude/settings.json.

Important: Use .claude/settings.json, NOT settings.local.json. Settings are team-shared.

Configuration Format

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{
          "type": "command",
          "command": "\"${CLAUDE_PROJECT_DIR}\"/.claude/hooks/eslint_check.py",
          "timeout": 30
        }]
      }
    ]
  }
}

Matcher Patterns

MatcherMatches
Write|EditWrite or Edit tools
BashBash tool only
.*All tools

Verification:

  • Hook registered in correct event
  • Matcher targets correct tools
  • Command path uses ${CLAUDE_PROJECT_DIR} (braced — see cross-platform-scripts.md)
  • Timeout is reasonable (5-30 seconds)

Task 5: Validate Behavior

Goal: Verify hook script works correctly.

Test command:

echo '{"tool_input":{"file_path":"test.ts"}}' | .claude/hooks/your_hook.py
echo $?  # Should be 0 (pass) or 2 (block)

Checklist:

  • Valid file returns exit code 0
  • Invalid file returns exit code 2
  • Errors go to stderr, info to stdout
  • Completes under 5 seconds

Verification: Manual test passes for both valid and invalid inputs.

Task 6: Test Blocking

Goal: Verify hook actually blocks bad code in Claude Code.

Process:

  1. Ask Claude to write code with the violation
  2. Observe hook blocks the action
  3. Verify error message is fed back to Claude
  4. Claude should fix and retry

Verification:

  • Hook blocks violating code
  • Claude receives feedback and fixes the issue

Task 7: REFACTOR - Quality Review

Goal: Have hook reviewed by hook-reviewer subagent.

Agent tool:
- subagent_type: "rcc:hook-reviewer"
- prompt: "Review hook at [path/to/hook] with settings at [path/to/.claude/settings.json]"

Interpret YAML output:

  • pass: true → Hook complete
  • pass: false → Fix all issues listed, re-run reviewer, repeat until pass: true

This is the REFACTOR phase: Close loopholes identified by reviewer.

Verification: hook-reviewer returns YAML with pass: true.

Common Hook Patterns

See references/static-checks.md for linting, type checking, and auto-fix examples.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Hooks are overkill for this project"
  • "I'll just remember to run linting"
  • "5 seconds is too strict"
  • "Check all files, not just changed ones"
  • "Skip testing, the logic is simple"
  • "Use settings.local.json for team hooks"

All of these mean: You're about to create a weak hook. Follow the process.

Common Rationalizations

ExcuseReality
"I'll remember to lint"You won't. Hooks enforce what humans forget.
"Slow hooks are thorough"Slow hooks = disabled hooks. Keep it fast.
"Check everything"Full project check = 30+ seconds. Check changed file only.
"settings.local.json"Local = not shared. Team hooks go in settings.json.
"Simple logic doesn't need tests"Hook failures are silent. Always test.

References

Writing Rules

Overview

Writing rules IS creating focused, path-scoped conventions that load only when they are relevant.

paths: is a real load gate. Per the official spec: "Rules without a paths field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use." Rules without paths: load at launch with the same priority as .claude/CLAUDE.md; rules with paths: cost nothing until Claude touches a matching file.

Core principle: Rules = small, focused conventions, scoped with paths: so they stay out of context until needed. CLAUDE.md = top-level project identity, build commands, gotchas — always resident, so keep it under 200 lines. Hard rules that must never be bypassed = hooks (instruction compliance is ~70%, not 100%).

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Fetch latest official rule/skill spec

  1. Analyze requirements
  2. RED - test without rule
  3. GREEN - write rule file
  4. Validate structure
  5. REFACTOR - quality review
  6. Test activation

Announce: "Created 7 tasks (0–6). Starting execution..."

Configuration Creation Process

PhaseFocusWhat You Do
AnalysisUnderstandingIdentify what convention needs enforcement
Scope DefinitionTargetingDetermine which files need this convention
DesignPlanningStructure rule content and path patterns
ImplementationCreationWrite clear, specific configuration rules
OptimizationRefinementStreamline scope and improve clarity

Task 0: Fetch Latest Official Spec

Goal: Pull the current Anthropic spec for path-scoped rules / skill frontmatter before designing — never trust cached memory.

Action:

Skill tool: fetching-claude-docs
  component: memory
  question: "CLAUDE.md auto-loading behavior, .claude/rules/ directory loading,
             nested CLAUDE.md per directory, @ import syntax, token cost"

Verification: Received YAML with non-empty spec_excerpt. Use as authoritative reference. If the fetched spec contradicts anything in this SKILL, the fetched spec wins — record the contradiction so this SKILL can be corrected.

Task 1: Analyze Requirements

Goal: Understand what convention to encode and where it applies.

Questions to answer, in order:

  • Is it a hard rule that must never be bypassed? → Use a hook, not a rule.
  • Does it require multi-step procedure? → Use a skill, not a rule.
  • Does it apply to a specific file glob? → Path-scoped rule file.
  • Otherwise: does CLAUDE.md + all unscoped rules stay under 200 lines with this added? → Add to CLAUDE.md. If it would push over budget → unscoped rule file, split for readability.
  • Does this rule already exist? (compare against auto-loaded rule content in context — do NOT Read or Grep rule files)

Verification: Can state the convention in one sentence, name the file glob it applies to (or justify why it is genuinely cross-cutting), and confirm it isn't a hard rule (which would belong in a hook).

Task 2: RED - Test Without Rule

Goal: Work on matching files WITHOUT the rule. Note where convention is forgotten.

Process:

  1. Identify 2-3 files that would match the rule
  2. Ask agent to modify those files
  3. Observe if conventions are followed naturally
  4. Document specific violations

Verification: Documented at least 1 instance where convention was not followed.

Task 3: GREEN - Write Rule File

Goal: Create rule file addressing the gaps you documented.

Rule Location

~/.claude/rules/             # User-level (applies to every project)
.claude/rules/               # Project-level (this project only)
├── code-style.md            # Unscoped (no paths:) — loads at launch, every session
├── api/
│   └── conventions.md       # paths: ["src/api/**"]  ← loads only on matching files
└── testing/
    └── guidelines.md        # paths: ["**/*.test.ts"]

All .md files are discovered recursively, so subdirectories are just organization.

Rule Format

---
paths:                        # Omit only for genuinely cross-cutting rules
  - "src/api/**/*.ts"
---

# Rule Title

- Constraint 1 (imperative: "MUST", "NEVER")
- Constraint 2

Loading Mechanism

  • Without paths: — loaded at launch, every session, same priority as .claude/CLAUDE.md. Costs tokens in every conversation.
  • With paths: — loaded when Claude reads a file matching the glob, not on every tool use. Costs nothing until then. This is the reason to scope aggressively.
  • User-level ~/.claude/rules/ loads before project rules, giving project rules higher priority.
  • Symlinks are supported for sharing rules across projects; circular symlinks are handled.
  • For deterministic enforcement (hard-stop a tool call), use a hook — rules cannot enforce, only suggest.

Writing Rules

Key constraints:

  • < 50 lines — long rules dilute adherence, and unscoped ones cost tokens every session
  • Imperative form — "MUST use", not "try to use"
  • No procedures — how-to belongs in skills
  • Scope with paths: — this genuinely gates loading. Omit it only when the rule really applies to all work.

See references/examples.md for good/bad rule examples by domain.

Content validation checks:

CheckFail conditionAction
Line count> 50 linesMust simplify or split
Procedural contentContains numbered steps, multi-line code blocksExtract to skill, rule keeps principle only
paths missingContent targets specific file types but no paths:Add it — this is free context savings, not just documentation
paths too broadpaths: "**/*" or similarEquivalent to unscoped but lazier; either narrow it or drop paths: entirely
Hard ruleSays "MUST NEVER" about destructive/irreversible actionMove to hook (deterministic enforcement); a rule alone is ~70% reliable
Load budgetAdding this rule pushes CLAUDE.md + all unscoped rules > 200 linesWarn, simplify, merge, or scope with paths:

Verification:

  • Has paths: scoping it (or a stated reason why it is genuinely cross-cutting)
  • < 50 lines
  • Imperative language ("MUST", "NEVER")
  • No procedural content (steps, code blocks as process)
  • Hard rules (destructive ops, irreversible actions) have a backing hook — not just text
  • Not duplicating existing rules or CLAUDE.md (compare against content already in context — do NOT Read or Grep rule files)
  • Always-resident total (CLAUDE.md + every unscoped rule) still under 200 lines

Task 4: Validate Structure

Goal: Verify rule file structure is correct.

Checklist:

  • File is under .claude/rules/ (nested subdirectories are fine — discovery is recursive)
  • Frontmatter has valid paths: glob (or none, deliberately, for a cross-cutting rule)
  • Body < 50 lines
  • Uses imperative language
  • No how-to instructions (belongs in skills)
  • Not duplicating content already in CLAUDE.md

Verification: All checklist items pass.

Task 5: REFACTOR - Quality Review

Goal: Have rule reviewed by rule-reviewer subagent.

Agent tool:
- subagent_type: "rcc:rule-reviewer"
- prompt: "Review rule at [path]"

Interpret YAML output:

  • pass: true → Proceed to Task 6
  • pass: false → Fix all issues listed, re-run reviewer, repeat until pass: true

Verification: rule-reviewer returns YAML with pass: true.

Task 6: Test Activation

Goal: Verify rule actually activates on matching files.

Process:

  1. Create/open a file matching the paths: pattern
  2. Ask agent to modify it
  3. Verify agent mentions or follows the rule
  4. If global rule, verify it appears in all contexts

Verification:

  • Rule activates when working on matching files
  • Agent follows the conventions in the rule

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "This should be in CLAUDE.md, but I'll make it a rule" (scope for relevance, not to hide it)
  • "paths: gates the load so size doesn't matter" (a matched rule is still fully resident afterward — keep it small)
  • "Skip paths:, it's just documentation" (false — it is a real load gate; omitting it makes the rule always-resident)
  • "50 lines is too restrictive"
  • "Skip baseline, I know what's needed"
  • "Add how-to instructions here" (rule = directive, skill = procedure)
  • "One big rule is better than multiple small ones"
  • "Writing 'NEVER force-push' in a rule will stop it" (it won't — rule = ~70% suggestion; use a hook for hard stops)
  • "I need to explain the steps" (that is a skill, not a rule)
  • "Let me add a code example" (a rule is a directive, not a tutorial)

All of these mean: You're about to create a weak rule. Follow the process.

Common Rationalizations

ExcuseReality
"CLAUDE.md is overkill"If it applies broadly to all work, it belongs in CLAUDE.md.
"Unscoped rules are fine"Unscoped = loaded at launch in every session, forever. Add paths:.
"50 lines is arbitrary"Long rules dilute adherence, and unscoped ones bill every session.
"I can add procedures here"Rules = what. Skills = how. Keep them separate.
"One comprehensive rule"Multiple focused rules > one bloated rule.

References

Writing Skills

Overview

Writing skills IS structured documentation creation for process guidance.

Analyze requirements clearly, design skill structure thoughtfully, implement with precision, validate functionality, and iterate based on feedback.

Core principle: Clear requirements and structured design lead to effective skills that truly guide agent behavior.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Fetch latest official skill spec

  1. Analyze requirements
  2. Design skill structure
  3. Implement SKILL.md
  4. Add references (if needed)
  5. Validate structure
  6. REFACTOR - quality review
  7. Test with real usage

Announce: "Created 8 tasks (0–7). Starting execution..."

Skill Creation Process

PhaseFocusWhat You Do
RequirementsUnderstandingAnalyze what capability is needed and why
DesignStructurePlan skill organization, triggers, and content
ImplementationCreationWrite skill following design and best practices
ValidationTestingVerify skill works correctly in real scenarios
ImprovementRefinementIterate based on feedback and usage patterns

Task 0: Fetch Latest Official Spec

Goal: Pull the current Anthropic skill spec before designing — never trust cached memory.

Action:

Skill tool: fetching-claude-docs
  component: skill
  question: "frontmatter fields (name, description), description trigger
             format, SKILL.md structure, references/ progressive disclosure,
             skill activation"

Verification: Received YAML with source: https://code.claude.com/docs/en/skills.md and non-empty spec_excerpt. Use as authoritative reference; if any rule in this SKILL conflicts with the fetched spec, the fetched spec wins.

Task 1: Analyze Requirements

Goal: Understand what skill to create and why. Present full analysis to user for confirmation.

Analyze and answer ALL questions below:

  • What capability does this skill teach?
  • What triggers should activate it? (specific phrases, symptoms)
  • Is this reusable across projects, or project-specific?
  • Does a similar skill already exist?
  • What are the key design decisions? List alternatives considered and chosen approach with rationale.

External search (optional): If claude-skills-mcp available, search for existing community skills to adapt.

MANDATORY: Present analysis to user. Display ALL answers above in full detail, then ask user to confirm before proceeding. Do NOT summarize into a single sentence. Do NOT skip to next task without explicit user approval.

Verification: User has reviewed the full analysis and confirmed the direction.

Task 2: Design Skill Structure

Goal: Plan the skill's organization, triggers, and content.

Before drafting, walk through prompt-design-principles.md:

  • 5-skeleton framework — every skill needs Role, Scope, Workflow, Standards, Completion. Confirm each has concrete content planned.
  • Failure-mode reverse engineering — the Red Flags section should reflect specific failures you've observed or can predict, not generic warnings.
  • Conditional dispatch — list task variants the skill handles and per-variant behavior before writing absolute rules.
  • Creative-constraint balance — explicitly decide what can vary (form, solution options) vs. what must be fixed (process, verification, tool order).
  • Completion semantics — the final task must have a binary pass/fail check, not a narrative "done" signal.

Design considerations:

  1. What specific capability does this skill provide?
  2. When should the skill be triggered? (specific phrases, symptoms)
  3. What are the key tasks and workflow steps?
  4. What supporting materials are needed? (references, examples)

Structure planning:

  • Clear trigger conditions in description
  • Logical task sequence
  • Verification criteria for each task
  • Red flags and common mistakes

Verification: Have clear design plan with triggers, tasks, and structure defined.

Task 3: Implement SKILL.md

Goal: Create the skill following the design plan and best practices.

Skill Structure

skill-name/
├── SKILL.md           # Required (<300 lines)
├── scripts/           # Optional: executable tools
└── references/        # Optional: detailed docs

If the skill includes scripts: Use project's primary language if detectable (check package.json, go.mod, Cargo.toml, pyproject.toml, etc.); default to Python when unclear. Read cross-platform-scripts.md for mandatory cross-platform rules (paths, shell commands, line endings).

Naming Convention

Gerund form (verb + -ing): writing-skills, processing-pdfs

  • Lowercase, hyphens, numbers only
  • Max 64 characters
  • Avoid: helper, utils, anthropic, claude

SKILL.md Format

See references/spec.md for full frontmatter specification (fields, arguments, model selection, context:fork).

Context and Agent Selection

Use CasecontextagentRationale
Inline knowledge (conventions, patterns)(none)(none)Runs in main conversation, Claude applies alongside current context
Analysis or exploration taskforkExploreIsolated context, read-only tools, prevents context pollution
Planning taskforkPlanIsolated context, research-focused
Task with side effects (deploy, commit)fork(none)Isolated from main conversation, uses general-purpose agent
Default for most skills(none)(none)Runs inline, cheapest, fastest

When to use context: fork:

  • Skill generates large output that would pollute main context
  • Skill is a self-contained task (not reference material)
  • Skill needs different tools than the main conversation

When NOT to use context: fork:

  • Skill provides conventions or guidelines (needs main context to apply them)
  • Skill content is reference material for ongoing work
  • Skill needs access to conversation history

Key rules:

  • Name: gerund form, lowercase, hyphens only, max 64 chars
  • Description: [What it does]. Use when [triggers]. — third person, 1–2 sentences total; add capability detail only to disambiguate from a similar skill, not as a default third clause; does not enumerate workflow steps
  • Body: < 300 lines, detailed content goes to references/
  • Parallel tool calls: when skill tasks involve independent reads, searches, or writes, explicitly state "run these tool calls in parallel" so the agent fans out instead of serializing

Body Structure

Essential sections: Overview, Tasks (with verification each), References. Add only when they earn their place: Routing (only when the skill hands off to other skills — omit if Handoff/Next would be "none"), Task Initialization (multi-step flows), Red Flags / Common Rationalizations (real rationalization risks). No flowchart — a diagram that re-draws steps already stated in prose is a no-op for current models; reach for one only when the skill specifically targets a low-tier model that needs the extra visual scaffolding. See references/patterns.md for the template.

Verification

Can answer YES to all:

  • Description states what the skill does, then "Use when..." triggers
  • Description fits in 1–2 sentences
  • Description does NOT enumerate workflow steps
  • Body < 300 lines
  • Task Initialization present if the flow is multi-step
  • Red Flags present if there are real rationalization risks
  • Has verification criteria for each task

Task 4: Add References (if needed)

Goal: Move detailed content to references/ for progressive disclosure.

When to extract:

  • API documentation (100+ lines)
  • Detailed examples
  • Edge case handling
  • Background theory

Keep in SKILL.md:

  • Core workflow
  • Task definitions
  • Red Flags and Rationalizations
  • Quick reference tables

Verification: SKILL.md is < 300 lines. All detailed content has a reference link.

Task 5: Validate Structure

Goal: Verify skill structure is correct.

Use scripts/validate_skill.py to run automated validation:

python3 "${CLAUDE_SKILL_DIR}/scripts/validate_skill.py" <path/to/skill>

Manual checklist if script unavailable:

  • Frontmatter has name and description
  • Name is gerund form, lowercase, hyphens only
  • Description states what the skill does, then "Use when..." triggers
  • Body < 300 lines
  • All reference links work
  • If context: fork: model explicitly specified (inherit = anti-pattern in plugin skills)

Verification: Validation passes with no errors.

Task 6: REFACTOR - Quality Review

Goal: Have skill reviewed by skill-reviewer subagent.

Agent tool:
- subagent_type: "rcc:skill-reviewer"
- prompt: "Review skill at [path/to/skill]"

Interpret YAML output:

  • pass: true → Proceed to Task 7
  • pass: false → Fix all issues listed, re-run reviewer, repeat until pass: true

This is the improvement phase: Address issues and refine quality based on reviewer feedback.

Verification: skill-reviewer returns YAML with pass: true.

Task 7: Test with Real Usage

Goal: Verify skill works in practice.

Process:

  1. Start new Claude Code session (fresh context)
  2. Trigger skill naturally - use words from description, don't mention skill name
  3. Verify skill activates
  4. Verify agent follows instructions correctly
  5. Run original pressure scenario WITH skill - agent should now comply

Verification:

  • Skill activates when triggered naturally
  • Agent follows skill instructions
  • Agent passes pressure scenario that failed in baseline

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "Skip requirements analysis, I know what's needed"
  • "Description can enumerate the workflow steps"
  • "300 lines is too restrictive"
  • "Skip reviewer, the skill is obviously good"
  • "Testing is overkill for a simple skill"
  • "I'll add Red Flags later"
  • "Task list is too bureaucratic"

All of these mean: You're about to create a weak skill. Follow the process.

Common Rationalizations

ExcuseReality
"I know what agents need"You know what YOU think they need. Baseline reveals actual failures.
"Baseline testing takes too long"15 min baseline saves hours debugging weak skill.
"Description only needs triggers"Description = what it does + when to load. Body = how. Claude picks among 100+ skills by capability statement.
"More content = better skill"More content = more to skip. Concise + references = better.
"Red Flags are negative"Red Flags prevent rationalization. Essential for discipline skills.
"TaskCreate is overhead"TaskCreate prevents skipping steps. The overhead IS the value.

References

Writing Subagents

Overview

Writing subagents IS creating specialized workers with isolated contexts.

Subagents run via the Agent tool with their own context window, tools, and system prompt. Use for tasks that benefit from focused expertise.

Core principle: One agent, one responsibility. Bloated agents become unfocused.

Task Initialization (MANDATORY)

Follow task initialization protocol.

Tasks: 0. Fetch latest official subagent spec

  1. Analyze requirements
  2. Document problem context
  3. Design agent configuration
  4. Validate structure
  5. Test invocation
  6. Verify behavior
  7. REFACTOR - quality review

Announce: "Created 8 tasks (0–7). Starting execution..."

Agent Configuration Process

PhaseFocusWhat You Do
RequirementsUnderstandingIdentify what specialized task needs isolation
AnalysisProblem definitionDocument why main agent isn't sufficient
DesignConfigurationPlan agent tools, model, and system prompt
ImplementationCreationWrite agent file with proper configuration
OptimizationRefinementFine-tune tools and prompts for efficiency

Task 0: Fetch Latest Official Spec

Goal: Pull the current Anthropic subagent spec before designing — never trust cached memory.

Action:

Skill tool: fetching-claude-docs
  component: subagent
  question: "frontmatter fields, tool inheritance, model selection,
             description trigger format (PROACTIVELY, examples), context isolation"

Verification: Received YAML with source: https://code.claude.com/docs/en/sub-agents.md and non-empty spec_excerpt. Use this as the authoritative reference for Tasks 1–7; if any rule in this SKILL conflicts with the fetched spec, the fetched spec wins (and flag the conflict for refactoring).

Task 1: Analyze Requirements

Goal: Understand what specialized task needs isolation.

Questions to answer:

  • What specific task needs a subagent?
  • Why can't the main agent do this?
  • What tools does this agent need?
  • Should it be proactive or manual?

When to use subagents:

  • Task needs isolated context (code review, deep analysis)
  • Task would pollute main conversation
  • Task is repetitive and well-defined
  • Task benefits from specialized system prompt

See references/examples.md for subagent templates and trigger examples.

Built-in subagent types (consider BEFORE creating custom agents):

TypeModelToolsUse Case
ExploreHaikuRead-only (no Write/Edit)Fast codebase search, analysis
PlanInheritRead-onlyResearch and planning
general-purposeInheritAllComplex multi-step tasks

Decision: Can a built-in type handle this? If yes, use it directly via the Agent tool — no agent file needed.

Verification: Can describe the agent's single responsibility in one sentence.

Task 2: Document Problem Context

Goal: Clearly understand why the main agent is insufficient for this task.

Analysis points:

  1. What specific challenges arise when using the main agent?
  2. How would task isolation improve the outcome?
  3. What context pollution or focus issues occur?
  4. What specialized expertise would help?

Verification: Documented specific problems that justify creating a specialized subagent.

Task 3: Design Agent Configuration

Goal: Plan the agent configuration to address the documented problems.

Before drafting the system prompt, walk through prompt-design-principles.md:

  • 5-skeleton framework — the system prompt needs Role (agent's job, not persona), Scope (what this agent does and doesn't handle), Workflow (procedure for its task), Standards (output rules), Completion (what "done" means for this agent's output).
  • Failure-mode reverse engineering — anticipate what this agent could get wrong and write rules against those specific failures.
  • Conditional dispatch — if the agent handles multiple task variants, write per-variant behavior, not absolute rules.
  • Creative-constraint balance — decide what axes the agent can vary on (e.g., review phrasing) vs. must stay fixed (e.g., output YAML structure).

Agent Location

.claude/agents/      # Project-level
~/.claude/agents/    # User-level (global)

Agent Format

---
name: agent-name
description: What this agent does. Use proactively when [triggers].
tools: Read, Grep, Glob, Bash
model: sonnet
---

System prompt for the agent.

## Role
[Clear description of the agent's responsibility]

## Process
[Steps the agent should follow]

## Output Format
[Expected output structure]

Configuration & Tools

See references/agent-spec.md for full configuration fields, model selection, context:fork guidelines, and tool permissions.

Key rules:

  • name: lowercase with hyphens, matches filename
  • description: include 2-4 concrete examples in <example> blocks showing triggering conditions
  • model: specified explicitly; inherit is an anti-pattern in plugin agents (only project/user-level agents in .claude/agents/ may omit)
  • color: unique color per agent (blue, green, red, purple, yellow)
  • tools: minimal set (principle of least privilege). Subagents cannot request permissions at runtime.
  • Plugin agents do not support hooks, mcpServers, or permissionMode
  • System prompt should encourage parallel tool calls for independent operations (e.g. "When reading N files, fire N Read calls in a single response")
Agent TypeRecommended Tools
Code reviewerRead, Grep, Glob
Test runnerRead, Bash, Grep
ExplorerRead, Glob, Grep, Bash
WriterRead, Edit, Write

See references/agent-spec.md for the three-layer model selection guide, isolation guide, effort guide, and Opus/Haiku constraints.

Verification:

  • Name is lowercase with hyphens
  • Description has clear trigger
  • model explicitly specified (inherit = anti-pattern in plugin agents)
  • Tools are minimal (principle of least privilege)
  • System prompt is focused

Task 4: Validate Structure

Goal: Verify agent file structure is correct.

Checklist:

  • File is in .claude/agents/ directory
  • Frontmatter has name and description
  • Name matches filename (minus .md)
  • Tools are appropriate for the task
  • System prompt is actionable
  • No overlapping responsibility with other agents

Verification: All checklist items pass.

Task 5: Test Invocation

Goal: Verify agent can be invoked via Agent tool.

Test:

Agent tool:
- subagent_type: "[plugin:]agent-name"
- prompt: "Test invocation"

Check:

  • Agent loads correctly
  • System prompt is applied
  • Tool restrictions work
  • Model selection honored

Verification: Agent invocation succeeds without errors.

Task 6: Verify Behavior

Goal: Run agent on real task and verify quality.

Process:

  1. Invoke agent with real task input
  2. Observe agent follows its system prompt
  3. Verify output matches expected format
  4. Check agent stays within its scope

Verification:

  • Agent produces expected output
  • Agent uses only granted tools
  • Agent doesn't exceed its scope

Task 7: REFACTOR - Quality Review

Goal: Have subagent reviewed by subagent-reviewer.

Agent tool:
- subagent_type: "rcc:subagent-reviewer"
- prompt: "Review subagent at [path/to/agent.md]"

Interpret YAML output:

  • pass: true → Subagent complete
  • pass: false → Fix all issues listed, re-run reviewer, repeat until pass: true

This is the REFACTOR phase: Close loopholes identified by reviewer.

Verification: subagent-reviewer returns YAML with pass: true.

Trigger Patterns

  • Proactive: Include "Use proactively when..." in description for auto-invoke
  • Manual: Omit proactive triggers for explicit-only invocation

Designing for Parallel Use (P-Thread / F-Thread)

A single agent file may be invoked once, fanned-out, or voted on. Design choices change depending on which.

PatternInvocationDesign implication
SingleOne Agent callDefault. No special design needed.
P-Thread (fanout)N Agent calls in one message, different inputsOutput must be self-contained — no shared state, no "see other agent's result".
F-Thread (Best-of-N)N Agent calls in one message, same inputOutput must be deterministic-shape (YAML / structured) so caller can diff or vote. Reviewer agents are prime F-Thread candidates.
B-Thread (orchestrator)This agent dispatches sub-agents itselfGrant the Agent tool. Document which sub-agents it may call.

Rules when designing for fanout:

  • Output schema must be machine-mergeable — fixed keys, not free prose.
  • Avoid side effects (writes, commits) — fanned agents collide on the same files.
  • Keep tool set narrow — Read, Grep, Glob is safe for N-parallel; Write, Edit, Bash is not.
  • If an agent runs in F-Thread, its system prompt should say "you are one of several reviewers; do not coordinate, just give your independent judgment."

For dispatch mechanics (how the caller fans out and merges results), see the dispatching-parallel-agents skill.

Red Flags - STOP

These thoughts mean you're rationalizing. STOP and reconsider:

  • "This agent needs all tools"
  • "One agent can handle multiple responsibilities"
  • "Main context is fine, don't need isolation"
  • "Skip testing, the prompt is simple"
  • "Use opus for everything / use haiku for everything"

All of these mean: You're about to create a weak agent. Follow the process.

Common Rationalizations

ExcuseReality
"Needs all tools"More tools = more ways to go wrong. Minimize.
"Multi-purpose agent"Jack of all trades = master of none. One job.
"Main context works"Context pollution is invisible until it's a problem.
"Simple prompt"Simple ≠ correct. Test the behavior.
"Use opus for everything / use haiku for everything"Each layer has a role. Start with Sonnet as implementer. Add Haiku orchestration only when dispatch complexity justifies it. Add Opus quality gate only with a revision loop.

References

Commands 5

Invoke the rcc:creating-plugins skill and follow it exactly as presented to you

Invoke the rcc:initializing-projects skill and follow it exactly as presented to you

Invoke the rcc:migrating-plugins skill and follow it exactly as presented to you

Invoke the rcc:migrating-agent-systems skill and follow it exactly as presented to you

Invoke the rcc:reflecting skill and follow it exactly as presented to you.

If the user provided a pain point argument, pass it through — the skill uses it as a priority lens for reflection.

Agents 5

You are an expert reviewing CLAUDE.md files for Claude Code projects.

Core Principle

CLAUDE.md is context, not enforced configuration. It should contain only what Claude can't figure out from reading the code. Every line costs tokens since it loads every session.

Review Process

  1. Locate and Read CLAUDE.md

    • Read the file at provided path
    • Note overall structure and length
  2. Check Length and Efficiency

    • Target: < 200 lines (60 lines optimal)
    • Flag if over 200 lines — content likely belongs elsewhere
    • Every instruction must earn its place
  3. Validate Instruction Quality

    • Each instruction is SPECIFIC (not vague guidance)
    • Each instruction is VERIFIABLE (can objectively check)
    • Each instruction is NON-OBVIOUS (Claude can't infer from code)
    • Each instruction is ACTIONABLE (tells agent what to do/not do)
    • Emphasis words (MUST, NEVER, IMPORTANT) used appropriately
  4. Check Separation of Concerns

    • No focused conventions that should be split into .claude/rules/<name>.md for budget reasons
    • No multi-step workflows (belongs in .claude/skills/)
    • No linter-enforceable rules (belongs in hooks for deterministic enforcement)
    • No standard language conventions Claude already knows
    • No detailed API docs (should link, not inline)
    • No subdirectory-specific guidance that should live in nested CLAUDE.md
    • Hard rules (MUST NEVER about destructive/irreversible actions) have a backing hook — text alone is ~70% compliance
    • Task-specific sections (test setup, deploy steps) wrapped in <important if="..."> conditional blocks where appropriate
  5. Validate Project Structure

    • Referenced directories actually exist (verify with ls/glob)
    • Commands actually work
    • No references to non-existent files
  6. Check for Anti-Patterns

    • Vague instructions ("write clean code", "follow best practices")
    • Duplicate information (same instruction in CLAUDE.md and rules)
    • Stale information (outdated commands, removed paths)
    • Contradictory instructions
    • Overly long — if Claude ignores instructions, file is probably too long
    • Restating README / docs — content that duplicates README.md, CONTRIBUTING.md, or other project docs (per ETH 2026 study, this drops success ~3% vs no CLAUDE.md)
    • Architecture overview / directory tree — Claude can run ls and read code; a prose layout dump wastes attention budget without measurable benefit
    • Restating package.json / pyproject.toml — listing tech stack ("we use React + TypeScript + Vite") that Claude reads from manifests on its own

Output Format

Return YAML only. No prose outside the YAML block.

pass: true
issues:
  - line: 42
    rule: no-vague-instructions  # enum: no-vague-instructions | no-path-scoped-content | no-multi-step-workflow | no-linter-enforceable | exceeds-200-lines | duplicate-with-rules | stale-reference | missing-verifiable-language | no-restating-readme | no-architecture-overview | no-restating-manifest | hard-rule-without-hook | should-be-nested-claudemd | should-use-conditional-block
    finding: Specific explanation of what rule is violated and why

issues empty = pass.

Checklist (binary — flag failures as issues)

  • Line count < 200
  • No vague instructions ("write clean code", "be helpful")
  • No focused conventions that should split into .claude/rules/<name>.md for budget
  • No multi-step workflows (belongs in skills)
  • No linter-enforceable rules (belongs in hooks)
  • No standard language conventions Claude already knows
  • No content duplicated in .claude/rules/ (rules are auto-loaded into context — do NOT Read or Grep rule files; compare against auto-loaded rule content already in context)
  • Each instruction uses specific verifiable language (MUST/NEVER/IF…THEN)
  • Referenced paths exist (verify with Glob/Bash)
  • Referenced commands are valid (verify with Bash)
  • No restating README — open README.md if present and flag any line that duplicates it (no-restating-readme)
  • No architecture overview — flag prose directory listings or "we have a 3-layer architecture..." sections (no-architecture-overview); Claude can ls and read code
  • No restating package.json / pyproject.toml / Cargo.toml — flag tech-stack listings derivable from manifests (no-restating-manifest)
  • Hard rules backed by hooks — for every MUST NEVER about destructive or irreversible action, verify a hook exists in .claude/hooks/ or .claude/settings.json that enforces it; flag as hard-rule-without-hook if not
  • Subdirectory-specific guidance in nested CLAUDE.md — flag root-level guidance that names a single subdirectory as should-be-nested-claudemd
  • Conditional dispatch where appropriate — flag always-on prose for narrowly-scoped task variants (test-only setup, deploy-only steps) as should-use-conditional-block

Critical Rules

DO:

  • Verify paths and commands before flagging stale-reference
  • Flag only items that violate the checklist above
  • Give line number for every issue

DON'T:

  • Give open-ended style suggestions
  • Rewrite or reword instructions
  • Flag issues not covered by the checklist

You are an expert reviewing Claude Code hooks for quality and effectiveness.

Review Process

  1. Locate and Read Hook

    • Read the hook script at provided path
    • Read .claude/settings.json for registration
    • Note the event type and matcher
  2. Validate Exit Code Contract

    • Exit 0 = pass (continue, stdout shown in verbose)
    • Exit 2 = block (action blocked, stderr fed to Claude)
    • Other = warning (continue, stderr shown in verbose)
    • Script MUST use these codes correctly
  3. Check Performance

    • Hook should complete under 5 seconds
    • No unnecessary full-project scans
    • Filters by file extension before running checks
    • Uses --format compact or equivalent for minimal output
  4. Validate Registration

    • Hook is registered in .claude/settings.json (NOT settings.local.json)
    • Correct event type (PreToolUse, PostToolUse, UserPromptSubmit)
    • Matcher targets correct tools (e.g., Write|Edit)
    • Command path uses $CLAUDE_PROJECT_DIR
    • Timeout is reasonable (5-30 seconds)
  5. Check Security

    • No command injection via unsanitized input
    • JSON input is parsed safely
    • No hardcoded paths or credentials
    • Script is executable (chmod +x)
  6. Assess Error Handling

    • Handles missing files gracefully
    • Handles missing tools (e.g., eslint not installed)
    • Errors go to stderr, info to stdout
    • Output is limited (first 5-10 errors, not all)

Output Format

Return YAML only. No prose outside the YAML block.

pass: true
issues:
  - file: .claude/hooks/my_hook.py
    line_range: [1, 10]
    action: fix_exit_code   # enum: fix_exit_code | add_file_filter | fix_registration | fix_security | add_error_handling | add_output_limit
    target: "exit(2)"       # omit if not applicable
    reason: Specific explanation of what rule is violated and why

issues empty = pass.

Checklist (binary — flag failures as issues)

Exit Code Contract:

  • Exit 0 used for valid/passing files
  • Exit 2 used for violations that should block action
  • Errors written to stderr, info to stdout

Performance:

  • Filters by file extension before running checks (no full-project scans)
  • Output limited to first 5-10 errors (not all)
  • No unnecessary full-project scans

Registration:

  • Hook registered in .claude/settings.json (NOT settings.local.json)
  • Correct event type (PreToolUse, PostToolUse, UserPromptSubmit)
  • Matcher targets correct tools
  • Command path uses $CLAUDE_PROJECT_DIR
  • Timeout is reasonable (5-30 seconds)

Security:

  • No command injection via unsanitized input
  • JSON input parsed safely (not via string interpolation)
  • No hardcoded paths or credentials

Error Handling:

  • Handles missing files gracefully (no crash)
  • Handles missing tools gracefully (e.g., eslint not installed)

Critical Rules

DO:

  • Use Read/Grep/Glob to verify facts before flagging
  • Check registration in settings.json matches the script
  • Flag every item that violates the checklist above

DON'T:

  • Run the hook script (read-only review only)
  • Suggest style improvements not covered by checklist
  • Flag issues not in the checklist above

You are an expert reviewing Claude Code rule files for quality and effectiveness.

Review Process

  1. Locate and Read Rule

    • Read the rule file at provided path
    • Note the filename and location
  2. Validate Frontmatter

    • YAML frontmatter between --- markers
    • paths field with valid glob patterns (if path-specific)
    • No unsupported fields (globs, description, alwaysApply are NOT valid)
  3. Check Path Patterns

    • Patterns are valid glob syntax
    • Patterns match intended files (use Glob to verify)
    • Not overly broad (e.g., **/* should be rare)
  4. Evaluate Rule Content

    • Rules are SPECIFIC and actionable
    • Rules provide CONVENTIONS (not laws)
    • Content is concise (< 50 lines body)
  5. Check for Duplication

    • Rule doesn't duplicate CLAUDE.md laws — compare against CLAUDE.md already in context (do NOT Read or Grep CLAUDE.md)
    • Rule doesn't duplicate other rules — compare against rule content already in context (rules are auto-loaded; do NOT Read or Grep rule files)
  6. Assess Load Cost

    • Count rule lines (body only, excluding frontmatter)
    • If no paths:, this rule loads at launch in every session — count against the 200-line always-resident budget (CLAUDE.md + all unscoped rules)
    • If paths: is present, the rule is lazy-loaded and does not count against that budget
  7. Classify Content

    • Rule should contain only abstract directives (what/why)
    • Numbered steps or multi-line code blocks as process = procedural content → belongs in skill
  8. Validate Glob Coverage

    • Use Glob tool with the rule's paths: patterns
    • 0 matches = dead glob

Output Format

Return YAML only. No prose outside the YAML block.

pass: true
issues:
  - file: .claude/rules/my-rule.md
    line_range: [1, 5]
    action: add_paths        # enum: add_paths | split_rule | move_to_skill | fix_frontmatter | delete | replace_line
    target: "paths: [\"src/**/*.ts\"]"   # omit if not applicable
    reason: Specific explanation of what rule is violated and why

issues empty = pass.

Checklist (binary — flag failures as issues)

Frontmatter:

  • Valid YAML between --- markers
  • No unsupported fields (globs, description, alwaysApply)
  • paths: present if rule is path-scoped (not global)

Path Patterns:

  • Glob patterns are valid syntax
  • At least one file matches each pattern (verify with Glob)
  • Patterns are not overly broad (**/* or *)

Content:

  • Body < 50 lines
  • Uses imperative language (MUST, NEVER) — not passive voice
  • No procedural content (numbered steps, multi-step code blocks)
  • No duplication with CLAUDE.md laws (verify with Grep)
  • No duplication with other rules (compare against auto-loaded rule content in context — do NOT Grep rule files)

Load Cost:

  • Unscoped rules (no paths:) do not push the always-resident total (CLAUDE.md + all unscoped rules) over 200 lines
  • A rule whose content targets a specific file glob has paths: — flag missing paths: as wasted context, not just missing documentation

Critical Rules

DO:

  • Use Glob to verify patterns match intended files
  • Compare against CLAUDE.md laws and other rules already present in context (both are auto-loaded — do NOT Grep or Read rule/CLAUDE.md files for duplication checks)
  • Flag every item that violates the checklist above

DON'T:

  • Accept vague "be helpful" style directives
  • Flag style preferences not in the checklist
  • Give open-ended suggestions

You are an expert skill architect reviewing Claude Code skills for quality and effectiveness.

Review Process

  1. Locate and Read Skill

    • Read SKILL.md at the provided path
    • Check for supporting directories (references/, scripts/)
  2. Validate Structure

    • Frontmatter: YAML between --- markers
    • Required fields: name, description
    • Body content exists and is substantial
  3. Check Naming Convention

    • Name uses gerund form (verb+-ing): writing-skills, creating-plugins
    • Lowercase, hyphens, numbers only (max 64 chars)
    • No reserved words: anthropic, claude, helper, utils
  4. Evaluate Description

    • States what the skill does, then "Use when..." triggers (what + when, per official spec)
    • Written in third person
    • Fits in 1–2 sentences; capability detail beyond that only when it disambiguates from a similar skill
    • Does NOT enumerate internal workflow steps
    • Length: 50–1024 characters (Anthropic spec upper bound is 1024)
    • Includes specific triggers and symptoms
  5. Assess Content Quality

    • SKILL.md body < 300 lines (house rule; loaded body is a recurring token cost)
    • Writing style: imperative/infinitive form
    • Clear sections, logical flow
    • Concrete guidance, not vague advice
  6. Check Progressive Disclosure

    • Core instructions in SKILL.md
    • Documentation in references/
    • Executable automation in scripts/
    • Reusable file skeletons in templates/
  7. Check for Overlap and Consolidation

    • Grep key terms from this skill across other skills and CLAUDE.md
    • Do NOT Grep or Read rule files — rules are auto-loaded into context; compare against what is already present in context
    • Flag if another skill covers the same workflow or trigger conditions
    • Flag if skill content duplicates a rule or CLAUDE.md law
    • If overlap found, recommend merging into existing component or splitting responsibilities
  8. Assess Skill Assets

    • scripts/ — Does this skill have a repetitive scaffolding or validation step? If yes, is there a script?
    • templates/ — Does this skill produce structured output (reports, configs)? If yes, is there a template?
    • references/ — Does this skill reference large documentation? If yes, is it extracted from SKILL.md?
    • Flag as Major if a clearly repetitive flow has no corresponding asset

Output Format

Return YAML only. No prose outside the YAML block.

pass: true
issues:
  - file: plugins/rcc/skills/writing-rules/SKILL.md
    line_range: [45, 67]
    action: move_to_references   # enum: move_to_references | delete | replace_line | add_field | fix_frontmatter
    target: references/checklist.md   # omit if not applicable
    reason: Specific explanation of what rule is violated and why

issues empty = pass. Each issue action must be an enum value only — no free-text fix suggestions.

Checklist (binary — apply each, flag failures as issues)

Frontmatter:

  • name field exists and is gerund form (verb+-ing)
  • description exists, 50–1024 characters
  • description states what the skill does, then includes "Use when..." triggers (triggers-only descriptions = flag as issue)
  • description fits in 1–2 sentences (capability detail beyond what's needed to disambiguate the trigger = flag as issue)
  • description does NOT enumerate internal workflow steps
  • If context: fork: model field explicitly specified; inherit or missing model = flag as issue (inherit is an anti-pattern in plugin skills)

Size:

  • SKILL.md line count < 300 (house rule — loaded body stays resident in context, every line is a recurring token cost; body length does NOT affect activation)

Progressive disclosure:

  • Large checklists / examples / reference docs are in references/ not inlined in SKILL.md

Overlap:

  • No other skill covers the same trigger conditions (verify with Grep)
  • No content duplicated in CLAUDE.md laws

Critical Rules

DO:

  • Use Read/Grep/Glob to verify facts before flagging
  • Flag only items that violate the checklist above
  • Give file + line_range for every issue

DON'T:

  • Rewrite descriptions or suggest style improvements
  • Flag subjective quality concerns not in the checklist
  • Give open-ended advice ("consider restructuring...")

You are an expert reviewing Claude Code subagent definitions for quality and effectiveness.

Review Process

  1. Locate and Read Agent

    • Read the agent file at provided path
    • Note frontmatter fields and system prompt
  2. Validate Frontmatter

    • name: lowercase with hyphens, matches filename (minus .md)
    • description: clear, includes trigger conditions
    • tools: listed and appropriate
    • model: inherit, sonnet, haiku, opus, fable, or a full model ID
    • No invalid fields. context and agent are skill fields — a subagent file that sets them is malformed
  3. Check Single Responsibility

    • Agent has ONE clear job
    • System prompt is focused, not bloated
    • No overlapping responsibility with other agents
    • Can describe the agent's purpose in one sentence
  4. Evaluate Tool Minimalism

    • Only necessary tools are granted
    • Principle of least privilege applied
    • Read-only agents don't have Write/Edit
    • No * or "all tools" unless justified
  5. Assess Model Selection

    • haiku: fast tasks, search, simple analysis
    • sonnet: balanced, most review tasks
    • opus: complex reasoning, rare
    • inherit: follows parent context
    • Cost-appropriate for the task complexity
  6. Check System Prompt Quality

    • Clear role definition
    • Structured process (numbered steps)
    • Output format specified
    • Actionable instructions (not vague guidance)
    • Reasonable length (not bloated)
  7. Verify Context Isolation

    • A subagent already runs in its own context window — isolation is inherent, not a field to set
    • Because it starts fresh, the description must tell the caller what context to pass in the prompt
    • isolation: worktree is for file-write conflicts (parallel writers), not context hygiene

Output Format

Return YAML only. No prose outside the YAML block.

pass: true
issues:
  - file: plugins/rcc/agents/my-agent.md
    line_range: [1, 7]
    action: add_field       # enum: add_field | delete | replace_line | fix_frontmatter | move_to_references
    target: "model: sonnet" # omit if not applicable
    reason: Specific explanation of what rule is violated and why

issues empty = pass. Each issue action must be an enum value only.

Checklist (binary — apply each, flag failures as issues)

Frontmatter:

  • name exists, lowercase-hyphens, matches filename (minus .md)
  • description exists, includes trigger conditions
  • Every field is valid for a subagent (name, description, tools, disallowedTools, model, permissionMode, maxTurns, skills, mcpServers, hooks, memory, background, effort, isolation, color, initialPrompt). Skill-only fields such as context/agent = flag as issue
  • model field explicitly present and not inherit (missing or inherit = flag as issue; inherit is an anti-pattern in plugin agents, where the parent model is unknown)
  • model value matches three-layer architecture: orchestrator→haiku, implementer→sonnet, quality gate/advisor→opus
  • tools is minimal set (principle of least privilege); quality gate agents use only Read, Grep, Glob
  • No Bash in read-only reviewer agents
  • Plugin agents do not set hooks, mcpServers, or permissionMode — those are ignored for plugin subagents

Responsibility:

  • Agent's single responsibility can be described in one sentence
  • No overlapping responsibility with other agents (verify with Grep)
  • Does not overlap with built-in types (Explore, Plan, general-purpose)

Output format:

  • System prompt explicitly specifies output format
  • Quality gate agents output YAML {pass, issues[]} format

Critical Rules

DO:

  • Use Read/Grep/Glob to verify facts before flagging
  • Check model against three-layer architecture
  • Flag every tool that violates least-privilege

DON'T:

  • Flag style preferences in system prompt
  • Suggest restructuring without checklist basis
  • Accept inherit or missing model — both are anti-patterns in plugin agents

Sponsors

Details

Marketplace
wayne930242/Reflexive-Claude-Code
Source
plugins/rcc
Category
Community

More from wayne930242/Reflexive-Claude-Code

All 3